querySelector and querySelectorAll – Selectors API

Hi,

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

<html>
<head>
    <title>Selectors API</title>
    <script>
        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");
        }

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

More details

http://msdn.microsoft.com/en-us/ie/cc307217.aspx

http://msdn.microsoft.com/en-us/library/cc288326(v=vs.85).aspx

Browser supported

http://caniuse.com/queryselector


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