javascript selectors

  • querySelector() returns the first DOM element that matches the specified group of selectors; IE 8+
  • querySelectorAll() returns a list (array) of the elements that match the specified group of selectors; IE 8+

var i, matches, match;
 
matches = document.querySelectorAll('div.note, div.info');
for (i = 0; i < matches.length; i++) {
    matches[i].innerHTML = 'UPDATED with querySelectorAll';
}
 
match = document.querySelector('div.alert'); // updates only first item
match.innerHTML = 'UPDATED with querySelector';
<div class="note">note text</div>
<div class="alert">alert text</div>
<div class="info">info text</div>
<div class="note">note text</div>
<div class="alert">alert text</div>
<div class="alert">alert text</div>
<div class="note">note text</div>
<div class="info">info text</div>

Leave a Reply

Your email address will not be published. Required fields are marked *