querySelector() and querySelectorAll() are two JavaScript functions very useful when working with HTML elements and JavaScript.
With these functions you can get in JavaScript the HTML elements according to a group of CSS selectors ("id", "class").
They are supported by: Mozilla Firefox 3.5+, Google Chrome, Internet Explorer 8+, Opera 10+, Safari 3.2+.

querySelector()

querySelector() returns the first element within the document that matches the specified group of selectors, or null if no matches are found.
Syntax:
var elm = document.querySelector('selectors');
- "selectors" is a string containing one or more CSS selectors separated by commas.
- elm is an element object.

Example, the code below displays an Alert window with the content of the HTML tag with id="someid", and the content of the first LI with class="aclass".
<div id="someid">Have a Good life.</div>
<ul>
 <li class="aclass">CoursesWeb.net</li>
 <li>MarPlo.net</li>
 <li class="aclass">php.net</li>
</ul>

<script type="text/javascript">
var someid_cnt = document.querySelector('#someid').innerHTML;
var aclass1_cnt = document.querySelector('li.aclass').innerHTML;

alert(someid_cnt +'\n'+ aclass1_cnt);
</script>

querySelectorAll()

querySelectorAll() returns a list of the elements that match the specified group of selectors. The object returned is a NodeList.
If the "selectors" string contains a CSS pseudo-element, the returned elementList will be empty (WebKit browsers have a bug: when the selectors string contains a CSS pseudo-element, the returned elementList contains the <html>).
Syntax:
var elementList = document.querySelectorAll('selectors');
- "selectors" is a string containing one or more CSS selectors separated by commas.
- elementList is a NodeList of element objects.

Example, creates an Array with the content of LI tags with class="sites", and the tags with class="note" within element with id="idata":
<ul>
 <li class="sites">CoursesWeb.net</li>
 <li class="sites">MarPlo.net</li>
 <li>php.net</li>
</ul>
<div id="idata">
 <span class="note">Web Development Courses</span>
 <span class="note">querySelector and querySelectorAll</span>
</div>

<script type="text/javascript">
// gets all the LI tags with class="sites", and the tags with class="note" in element with id="idata"
var elm_list = document.querySelectorAll('li.sites, #idata .note');
var nr_elm = elm_list.length;         // number of elements in elm_list

var arr_cnt = [];       // array to contain data from elm_list

// traverse the elm_list object, and add in arr_cnt the content of each element
for(var i=0; i<nr_elm; i++) {
  arr_cnt.push(elm_list[i].innerHTML);
}

// test, shows data stored in arr_cnt
alert(arr_cnt);
</script>
- Click the button "Test" to see the result.

The difference between querySelector() and querySelectorAll() is that querySelector() returns a single object with the first HTML element that matches the "selectors", but querySelectorAll() returns a list of objects with all the HTML elements that match the "selectors".


• To limit the search to descendants of an element only, you can call the selectors API on the specific element of interest.
elementObject.querySelector('selectors')

elementObject.querySelectorAll('selectors')

- Here's another example with querySelectorAll(), the selection is made on other element, not on "document". When the mouse cursor is over a selected <a>, the URL address is added into a specified DIV.
<div id="seeurl">Shows the URL.</div>
<ul id="sites">
 <li><a href="http://coursesweb.net/javascript/" title="JavaScript Course">JavaScript Course</a></li>
 <li><a href="http://www.marplo.net/" title="Courses, Games, Anime">Courses, Games, Anime</a></li>
</ul>

<script type="text/javascript">
// gets A tags in LI added in element with id="idata"
var elm_list = document.getElementById('sites').querySelectorAll('li a');
var nr_elm = elm_list.length;         // number of elements in elm_list

// traverse the elm_list object
for(var i=0; i<nr_elm; i++) {
  // register onmouseover event to add in #seeurl the "href" of each selected <a>
  elm_list[i].onmouseover = function() {
    document.getElementById('seeurl').innerHTML = this.href;
  }

  // register onmouseout event to add in #seeurl a default text
  elm_list[i].onmouseout = function() {
    document.getElementById('seeurl').innerHTML = 'Shows the URL.';
  }
}
</script>
- Demo. Position the mouse cursor over each link.
Shows the URL.

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which type of <input> creates input fields that should contain a numeric value?
type="text" type="number" type="date"
<input type="number" name="points" min="5" max="80" />
Which CSS property allows to change the transparency of an element?
font-style opacity color
#id {
  filter:alpha(opacity=40);    /* for IE */
  opacity:0.4;
}
Click on the function that formats a number to specified number of characters.
toPrecision() exp() toFixed()
var num = 12.34567;
alert( num.toPrecision(3) );       // 12.3
Which function randomizes the order of the elements into an array?
natsort() shuffle() sort()
$lang = array(10=>"PHP", 20=>"JavaScript", "site"=>"coursesweb.net");
shuffle($lang);
var_export($lang);     // array (0=>"coursesweb.net", 1=>"PHP", 2=>"JavaScript")
querySelector and querySelectorAll

Last accessed pages

  1. JavaScript Course - Free lessons (10060)
  2. Zodiac Signs PHP code (1975)
  3. Courses Web: PHP-MySQL JavaScript Ajax HTML CSS Flash-AS3 (41458)
  4. $_GET, $_POST and $_REQUEST Variables (18585)
  5. Read Excel file data in PHP - PhpExcelReader (31772)

Top accessed pages

  1. Courses Web: PHP-MySQL JavaScript Ajax HTML CSS Flash-AS3 (41458)
  2. Read Excel file data in PHP - PhpExcelReader (31772)
  3. PHP-MySQL free course, online tutorials PHP MySQL code (31722)
  4. Get Attribute (ID, Class, Name, Title, Src) with jQuery (29002)
  5. PHP PDO - exec (INSERT, UPDATE, DELETE) MySQL (25979)