web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Dynamics 365 Community / Blogs / Nishant Rana’s Weblog / querySelector and querySele...

querySelector and querySelectorAll – Selectors API

Nishant Rana Profile Picture Nishant Rana 11,325 Microsoft Employee

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


Filed under: HTML 5, JavaScript Tagged: HTML 5, JavaScript

This was originally posted here.

Comments

*This post is locked for comments