IE 8 New way to select objects using CSS selectors
When we wish to set some styling rules to a certain group on html controls on a given page - the proper way to do it is to use CSS selectors. CSS selectors come in many ways , You can write simple selector, complex selectors and even group them together.
Basically Selectors are the patterns that determine which style rules apply to elements of the document tree.
Lets see some sample:
Type element selectors: Will find all the div elements and set their font size to 22px
div{
font-size:22px;
}Class Selector: Will find all the p elements that has a class attribute of "wrpa"
and set their some properties.
p.wrap
{
text-align: center;
color: red;
}ID selector: Will find all the elements that with the Wrap as ID.
#WRAP
{
background-color: silver;
border-color: gray;
}
Descendent Selector: will find all the elements that are immediate or not immediate child of ...
h1 em{ color: red}
Now what is we wish to use this selectors syntax and find those elements using JavaScript.
Well It is now possible using IE 8 JavaScript new features.
The document object has now new 2 functions :
1. document.querySelectorAll(selectorStr)
2. document.querySelector(selectorStr)
For example, Lets say I have the following HTML:
<div id="div1">aaa</div>
<div class="SomeClass">bbb</div>
<div class="SomeClass">ccc</div>
<input type=button id="btnTest" onclick="GoSelectors();" value="Go selectors">
And the following JavaScript code:
function GoSelectors()
{ var oDiv = document.querySelector("#div1");
var oDivs = document.querySelectorAll("div.SomeClass");
alert(oDiv.id);
alert(oDivs.length);
}
The first js statement will return the div object with the id "div1" and the second statement will return all the div object with the given class name.
To read more:http://msdn.microsoft.com/en-us/library/cc288326(VS.85).aspx