1. childNodes and nodeType
childNodes gets the child nodes, but the space between one label and another label will be calculated as text nodes. nodeType determines what type of node a node is. Only when nodeType==1 is the element node, 2 is the attribute node, and 3 is the text node.
2. Children gets child nodes. It only returns HTML nodes, not even text nodes. Although it is not a standard DOM attribute, it is the same as the innerHTML method and is supported by almost all browsers.
3. offsetParent obtains the positioned parent element node of the node.
4. FirstChild() and firstElementChild() have compatibility issues. Use if to deal with compatibility issues. The rest of lastchild and so on are similar to this.
5. Use dom to get element attributes, use setAttribute('attribute to be set', 'set attribute value'), removeAttribute(name), getAttribute(name), which are basically not commonly used. But there are also situations where it must be used.
6. Using className to select elements can encapsulate a simple method. This is a low version now and has no bugs, but it has strong limitations.
<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <p id="p1"> <ul> <li class="box"></li> <li></li> <li></li> <li class="box"></li> <li class="box"></li> <li></li> <li></li> <li class="box"></li> </ul> </p> </body> <script> function getByClass(oParent,sClass){ //*号代表通配符 var aResult=[]; var aEle = oParent.getElementsByTagName('*'); for(var i=0;i<aEle.length;i++){ if(aEle[i].className==sClass){ aResult.push(aEle[i]); } } return aResult; } var p1 = document.getElementById('p1'); var aBox = getByClass(p1,'box'); for(var i=0;i<aBox.length;i++){ aBox[i].style.backgroundColor='red'; } </script></html>
7. Create nodes such as forum functions
Be sure to add the created node to his parent element
creatElement() to create the node
appendChild() to add the created node to his parent element before
insertBefore() in a certain Insert a node before
removeChild() to delete a node
<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title>创建节点</title> <script> window.onload=function(){ var oUl = document.getElementById('oUl'); var oBtn = document.getElementById('btn'); var input1 = document.getElementById('input1'); var aLi = document.getElementsByTagName('li'); oBtn.onclick=function(){ var oLi = document.createElement('li'); oLi.innerHTML=input1.value; if(aLi.length>0){ oUl.insertBefore(oLi,aLi[0]); }else{ oUl.appendChild(oLi); } } } </script> </head> <body> <p> <input id="input1" type="text" /> <input id='btn' type="button" value="创建" /> <ul id='oUl'> </ul> </p> </body></html>
Related recommendations:
Deep into the advanced application of DOM in JavaScript
Summary of native JavaScript operations on dom nodes
The above is the detailed content of Sharing of DOM knowledge points in js. For more information, please follow other related articles on the PHP Chinese website!