How to operate DOM elements in js

小云云
Release: 2018-03-26 16:09:38
Original
1932 people have browsed it

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');
Copy after login

2. Selector

var ele1 = document.querySelector('{.className/#id/tagName}'); var eleList = document.querySelectorAll('.className,#id,p');
Copy after login
var ele2 = document.getElementById('{id}') var ele3 = document.getElementByClassName('{className}'); var ele4 = document.getElementByTagName('{tagName}');
Copy after login

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;
Copy after login

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(); //是否有属性设置
Copy after login

5. DOM modification

ele.appendChild('elc'); ele.removeChild('elc'); ele.replaceChild('elc1','elc2'); ele.insertBefore('elc','refElc'); //插入到子节点refElc节点之前 ele.cloneNode(true); //该参数表示被复制的节点是否包括所有属性和子节点
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!