Home  >  Article  >  Web Front-end  >  What are the ways to manipulate DOM in JavaScript?

What are the ways to manipulate DOM in JavaScript?

coldplay.xixi
coldplay.xixiOriginal
2020-06-30 14:41:084197browse

The methods for JavaScript to operate DOM are: 1. Get nodes, the code is [document.getElementById();]; 2. CSS selector, the code is [document.querySelector()]; 3. Document structure, The code is [parentNod].

What are the ways to manipulate DOM in JavaScript?

The methods for JavaScript to operate DOM are:

 1. Get the node

document.getElementById();//id=""
document.getElementsByName();//name=""
document.getElementsByTagName();//"input"
document.getElementsByClassName();//class=""

 2. CSS selector

document.querySelector();//根据css选择器规则返回第一个匹配到的元素,"#div1>p"
document.querySelectorAll();//返回所有匹配到的元素

 3. Document structure

//(1)作为节点数的文档
    parentNode    //获取该节点的父节点   
    childNodes    //获取该节点的子节点数组
    firstChild    //获取该节点的第一个子节点
    lastChild    //获取该节点的最后一个子节点
    nextSibling    //获取该节点的下一个兄弟元素
    previoursSibling    //获取该节点的上一个兄弟元素
    nodeType    //节点的类型,9代表Document节点,1代表Element节点,3代表Text节点,8代表Comment节点,11代表DocumentFragment节点
    nodeVlue    //Text节点或Comment节点的文本内容
    nodeName    //元素的标签名(如P,SPAN,#text(文本节点),DIV),以大写形式表示
    //注意,以上6个方法连元素节点也算一个节点
//(2)作为元素树的文档
    firstElementChild        //第一个子元素节点
    lastElementChild        //最后一个子元素节点
    nextElementSibling        //下一个兄弟元素节点
    previousElementSibling    //前一个兄弟元素节点
    childElementCount        //子元素节点个数量
    //注意,此5个方法文本节点不算进去

 4. JavaScript operation DOM

document.getElementById("img1").alt;       // 获取alt属性
document.getElementById("img1").src=""; //设置src属性
document.getElementById("img1").setAttribute("src", "1small.jpg");//非标准
document.getElementById("img1").getAttribute("class");//非标准
document.getElementsByClassName("cnblogs_code")[0].attributes;//返回节点的所有属性

 5. Element content and node creation

innerText、textContent //innerText与textContent的区别,当文本为空时,innerText是"",而textContent是undefined
innerHTML
document.createTextNode("

我是一个javascript新建的节点

"); document.createElement("p");//创建p节点 appendChild(); //将一个节点插入到调用节点的最后面 insertBefore(); //接受两个参数,第一个为待插入的节点,第二个指明在哪个节点前面,如果不传入第二个参数,则跟appendChild一样,放在最后。 removeChild(); //由父元素调用,删除一个子节点。注意是直接父元素调用,删除直接子元素才有效,删除孙子元素就没有效果了。 replaceChild(); //删除一个子节点,并用一个新节点代替它,第一个参数为新建的节点,第二个节点为被替换的节点 cloneNode(); //克隆节点,参数true document.getElementById("div1").style.backgroundColor="#fff";

Related learning recommendations: javascript video tutorial

The above is the detailed content of What are the ways to manipulate DOM in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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