JavaScript DOM Selectors
JavaScript DOM Selectors are used to select and manipulate HTML elements within a document. There are 6 ways to select HTML elements using DOM selectors.
getElementById()
The getElementById()
method used to return the matching element with given ID name.
Example
<input type='text' id='txt' value='Sample Text'> <input type='button' onclick='get_val()' value='Click'> <p id='output'></p> <script> function get_val(){ var v=document.getElementById("txt").value; document.getElementById("output").innerHTML="Entered value is <b>"+v+"</b>"; } </script>Try it Yourself
getElementsByClassName()
The getElementsByClassName()
method used to return all matching elements with the given class name.
Example
<p><input type='number' class='num' value='10'></p> <p><input type='number' class='num' value='20'></p> <p><input type='number' class='num' value='30'></p> <input type='button' onclick='get_total()' value='Click'> <p id='output'></p> <script> function get_total(){ var ele=document.getElementsByClassName("num"); var tot=0; for(i=0;i<ele.length;i++){ tot+=Number(ele[i].value); } document.getElementById("output").innerHTML="Total is <b>"+tot+"</b>"; } </script>Try it Yourself
getElementsByTagName()
The getElementsByTagName()
method used to return all matching elements with the given tag name.
Example
<input type='button' onclick='get_paras()' value='Click'> <p>Sample Text 1</p> <p>Sample Text 2</p> <p>Sample Text 3</p> <script> function get_paras(){ var ele=document.getElementsByTagName("p"); for(i=0;i<ele.length;i++){ ele[i].style.color='green'; ele[i].style.fontWeight='bold'; } } </script>Try it Yourself
getElementsByName()
The getElementsByName()
method used to return all matching elements with the given name (name attribute).
Example
<p><input type='number' name='num' value='10'></p> <p><input type='number' name='num' value='20'></p> <p><input type='number' name='num' value='30'></p> <input type='button' onclick='get_total()' value='Click'> <p id='output'></p> <script> function get_total(){ var ele=document.getElementsByName("num"); var tot=0; for(i=0;i<ele.length;i++){ tot+=Number(ele[i].value); } document.getElementById("output").innerHTML="Total is <b>"+tot+"</b>"; } </script>Try it Yourself
Method | Description |
---|---|
querySelector() | Used to return the first matching Element. |
querySelectorAll() | Used to Return all matching Elements. |