querySelector and querySelectorAll – Selectors API


Apart from our usual document.getElementsById and document.getElementsByTagName method to select element from the DOM we can now make use of document.querySelector and document.querySelectorAll .

With them we can use the same selectors that we use in CSS to select elements for styling.

A simple example

    <title>Selectors API</title>
        window.onload = function () {

            // select div element with id myDivId
            var myDiv = document.querySelector("#myDivId");

            // select p element with text "Paragraph 1"
            var paragraph1 = myDiv.querySelector("span>p");

            // select p element having class as p1Class
            var paragraph2 = document.querySelector("p.p2Class");

            // select all p element
            var allParagraph = document.querySelectorAll("div>span>span>p");

    <div id="myDivId" class='divClass'>
        <span><span class='spanClass'>
                Paragraph 1</p>
            <p id="p2" class="p2Class">
                Paragraph 2</p>

More details



Browser supported


Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

Share your thoughts

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s