添加元素

var ulbox =document.getElementByTagName("ul")[0];

function addElement (obj,cont){
   var newli = docuemnt.creatElement("li");
   newli.setAttribute("class","newli");
   newli.innerHtml= cont;
   obj.appendChild(newli);
}
addElement (ulbox ,"WHAT MEAN");




    <ul class="ul">
          <li class="last">last li</li>
    </ul>
    <button>add new li<button>
    <script> btn.onclick=function () { creatEle(ulbox,lili,"hi") } function creatEle(obj,who,cont) { var newLi = document.createElement("li"); newLi.setAttribute("class", "newli"); newLi.innerHTML = cont; obj.insertBefore(newLi,who); } </script>

但并没有insertAfter ,需要自己写

function insertAfter(newElement,targetElement) {  
    var parent = targetElement.parentNode;  
    if(parent.lastChild == targetElement)  
    {  
        parent.insertBefore(newElement);  
        }  
    else  
    {  
          parent.insertBefore(newElement,targetElement.nextSibling);  
        }  
  }  
function addWhat (obj,objtype,cont){
   var newele = document.createElement(objtype);
   newele.setAttribute("class","newone");
   newele.innerHTML=cont;
   obj.appendChild(newele);

}

addWhat (divbox,"span","try this result")

你可能感兴趣的:(添加元素)