Query Selector Example
querySelector, querySelectorAll, for loop, innerHTML
by Matt Howey
HTML
<!--
This fiddle uses:
querySelector, querySelectorAll, innerHTML, for loop, arrays and setTimeout
-->
<div id="someDiv">
This is some div with an id...
</div>
<div class="someDiv">
This is some div with a class...
</div>
<div class="someDiv">
Test
</div>
<p class="someDiv">
This is a paragraph, but it will still be matched by querySelectorAll() if I don't specify the tag type because it's a paragraph with the same class as the <divs></divs>
</p>
</p>
JavaScript
// play with the positioning (in the code) and timing of this settimeout to test "race conditions" with setTimeout
setTimeout(function() {
document.getElementById("someDiv").innerHTML = "I WIN!! (1 seconds)";
},1000);
setTimeout(function() {
document.querySelector("#someDiv").innerHTML = "I'm a div with Identity! (1 second)";
},1000);
// using querySelectorAll to create an array of elements and
// use a for loop to iterate through them and set the innerHTML of each one
// jquery / sizzle simplifies this somewhat with convenience functions
// such as .each() to go through each selected element
setTimeout(function() {
var selected = document.querySelectorAll("div.someDiv");
// comment the one above and uncomment the one below ****
//var selected = document.querySelectorAll(".someDiv");
for(var i=0; i<selected.length; i++) {
selected[i].innerHTML = "My Inner HTML was replaced because I was matched! (2 seconds)";
}
},2000);