Home > Article > Web Front-end > How to operate DOM elements in js
DOM node (node) generally corresponds to a label, a text version or an HTML attribute. DOM nodes have a nodeType attribute used to represent the enumeration type of the current element, {1:Element,2:Attribute,3:Text}. This article mainly shares with you the operation methods of DOM elements in js. I hope it can help you.
1. Create DOM node
var node1 = document.createElement('p'); var node2 = document.createTextNode('Hello World');
2. Selector
var ele1 = document.querySelector('{.className/#id/tagName}'); var eleList = document.querySelectorAll('.className,#id,p');
var ele2 = document.getElementById('{id}') var ele3 = document.getElementByClassName('{className}'); var ele4 = document.getElementByTagName('{tagName}');
3. Parent-child sibling node
var parent = ele.parentElement; //父元素 parent = ele.parentNode; //只读父元素 var children = ele.children; var firstChild = ele.firstElementChild; firstChild = ele.firstChild; var lastChild = ele.lastElementChild; lastChild = ele.lastChild; var nextSibling = ele.nextSibling; var prevSiblint = ele.previousSibling;
4. Attribute
var attrs = ele.attributes; //获取所有属性 key-value var classes = ele.getAttribute('class'); //获取单一属性值 ele.setAttribute('class','className'); //设置属性 ele.hasAttribute('attrName'); //判断属性是否存在 ele.removeAttribute('attrName'); //移除属性 ele.hasAttributes(); //是否有属性设置
5. DOM modification
ele.appendChild('elc'); ele.removeChild('elc'); ele.replaceChild('elc1','elc2'); ele.insertBefore('elc','refElc'); //插入到子节点refElc节点之前 ele.cloneNode(true); //该参数表示被复制的节点是否包括所有属性和子节点
Related recommendations:
js DOM element ID is the global variable _DOM
The above is the detailed content of How to operate DOM elements in js. For more information, please follow other related articles on the PHP Chinese website!