querySelector and querySelectorAll – Selectors API
Views (340)
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.

Like
Report
*This post is locked for comments