DOM Find Elements
Find node objects by ID: document.getElementById(id)
Return value: (found) specified object (not found) output null
Find elements by tag name: document. getElements ByTagName (tagName)
Return value: (found) HTMLCollection (which contains element objects) Output HTMLCollection []
Note: This method is the only one that can be called by both document objects and node objects.
Find elements by class name: document. getElements ByClassName (className)
Return value: (found) HTMLCollection (which contains element objects) Output HTMLCollection []
Find elements by name: document. getElements ByName (name)
Return value: (found) HTMLCollection (which contains element objects) Output HTMLCollection []
Example: Finding Elements
<div> <p>Hello</p> <div>888</div> </div> <div class="one"></div> <input type="radio" name="sex">male <input type="radio" name="sex">female <div id="box"> <div>1</div> <div>2</div> </div> <div>hello</div> <p>world</p> <div>hi</div> <script type="text/javascript"> var o=document.getElementsByTagName('div'); console.log(o.length); //3 o[1].innerHTML='The second'; for(var i=0;i<o.length;i++){ console.log(i); //0 1 2 } //Find elements by class name var oo=document.getElementsByClassName('one'); console.log(oo,oo.length); //HTMLCollection [div.one] 1 o[0].innerHTML='Ha ha ha ha ha ha ha'; var ooo=document.getElementsByName('sex'); console.log(ooo); //NodeList(2) [input, input] var cz=document.getElementsByTagName('div'); cz[1]=innerHTML='Hello everyone'; var o1=document.getElementById('box'); var ds=o1.getElementsByTagName('div'); console.log(ds); //HTMLCollection(2) ds[0].innerHTML='Aha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha ha'; </script> </body>
QueySelector Finding Node Objects
Find page elements according to the specified selector
Selector: CSS Selector #box.one p
querySelectorAll: Find the educated object; Return value: NodeList
Note: If it's not an ID selector, just take the first one.
<body> <div id="box">Ha-ha</div> <div class="one">Ha-ha</div> <div class="one">Hey</div> <div id="box1"> <p>Ha ha ha</p> <div>Hello everyone</div> </div> <script type="text/javascript"> var o=document.querySelector('#box'; // Based on ID console.log(o); //<div id="box">haha</div> var o1=document.querySelector('.one');//Only one can be taken. console.log(o1); //<div class="one">ha </div> var os=document.querySelectorAll('#box'); console.log(os); //NodeList [div#box] var os1=document.querySelectorAll('.one'); console.log(os1); //NodeList(2) [div.one, div.one] var os2=document.querySelectorAll('div'); console.log(os2); //NodeList(5) [div#box, div.one, div.one, div#box1, div] var oo=document.querySelector('#box1 div'); console.log(oo); //< div > Hello everyone </div > var oo1=document.querySelectorAll('#box1 div'); console.log(oo1); //NodeList [div] </script> </body>