创建元素节点 :document.createElement(“p”); 创建text节点 :document.createTextNodet(“内容”); 复制一个节点: var newNode = node.cloneNode();//参数为true复制所有子节点,参数为false只执行一次浅复制。
removeChild();//该方法不是在待删除的节点上调用,而是在它的父元素节点上调用。 node.parentElement.removeChild(node); replaceChild();//删除一个子节点,并用一个新的节点取代它。第一个参数是新节点,第二个参数是要删除的节点。 node.parentElement.replaceChild(newNode,node);
Many times it is necessary to modify the nodeattributesandcontentto modify.
Modification of attributes
Attributes are divided into standard HTML attributes and non-standard HTML attributes.
*HTML attributes as attributes of Element
HTML Element defines common HTTP attributes, such as id, title lang and dir attributes, as well as event handler attributes (onclick). Specific element subtypes also have specific attributes, such as the src attribute of img.
var oImg = document.getElementById("img1");oImg.id = "newID";oImg.className = "className";oImg.src = "...";
Getting and setting non-standard HTML attributes
Element defines the getAttribute and setAttribute methods to query and set non-standard attributes, hasAttribute and removeAttribute to detect whether the named attribute exists and is complete Delete attributes.
Modifications to the content
innerHTML: Content containing tags
innerText (poor Firefox support): plain text element content
textContent (not supported by IE): plain text element content
##Find it in one step
document.getElementById() 返回对拥有指定 id 的第一个对象的引用。 document. getElementsByClassName() 返回文档中所有指定类名的元素集合。 document.getElementsByName() 返回带有指定名称的对象集合。 document.getElementsByTagName() 返回带有指定标签名的对象集合。
Find Father, Son and Brother
对于一个Node节点,包含很多种,像:Document节点、Text节点、Comment节点、Element节点,我们常常需要获得的是元素节点,忽略掉Text和Comment节点: firstElementChild,lastElementChild; children => 数组类型:children[0] ,第一个子节点 nextElementSibling,previousElementSibling => 兄弟节点 parentElement => 父亲节点
Node有方法appendChild()和insertBefore()。 parent.appendChild(child); // 插入到最后 parent.insertBefore(newNode,node);//插入到node之前
The above is the detailed content of Original JS implements adding, deleting, modifying, checking and inserting. For more information, please follow other related articles on the PHP Chinese website!