Header Ads

Finding Elements in JavaScript

Finding Elements in JavaScript
1.Finding HTML Element by ID : Lets find an HTML element with ID (id="intro")
document.getElementById("intro");
If the element is found the method will return the element as an object. Otherwise it will return null.

2.Finding HTML Element by Class Name : Lets find an HTML element with class name (class="intro")
document.getElementsByClassName("intro");
Finding elements by class name does not work in Internet Explorer 8 and earlier versions. 

3.Finding HTML Element by Tag Name : Lets find an HTML element with tag name (<p></p>)
document.getElementsByTagName("p");
It will return all the <p> elements.

4.Finding HTML Element by CSS Selectors : If you want to find all HTML elements that match a specified CSS selectors use the querySelectorAll() method.
document.querySelectorAll("p.intro");
This example returns a list of all <p>elements with class ="intro". You also can use querySelector() instead of querySelectorAll().
document.querySelector("p.intro");
But the only difference between querySelector() and querySelectorAll() is, in this example querySelector() returns only one <p>elements with class="intro" and querySelectorAll() returns a list of all <p> elements with class="intro"

No comments:

Powered by Blogger.