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').


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 the content of the first LI with class='aclass'.
<h4>Example querySelector()</h4>
<ul>
 <li>MarPlo.net</li>
 <li class='aclass'>CoursesWeb.net</li>
 <li class='aclass'>GamV.eu</li>
</ul>
<p style='background:#fbfbb0;'>If you click the following button (accessed with querySelector), it displays at #resp the content of the first LI with class='aclass'.</p>
<button id='btn1'>Click</button>
<blockquote id='resp'>#resp</blockquote>

<script>
var btn = document.querySelector('#btn1');
btn.addEventListener('click', (ev)=>{
 document.getElementById('resp').innerHTML = document.querySelector('li.aclass').innerHTML;
});
</script>

querySelectorAll()

querySelectorAll() returns an array of objects with the elements that match the specified group of selectors.
Syntax:
var elms = document.querySelectorAll('selectors');
- 'selectors' is a string containing one or more CSS selectors separated by commas.
- elms is an array with the selected HTML elements.

Example, gets an Array with the content of LI tags with class='sites', and the tags with class='note' within element with id='dv1', then it displays their content:
<h4>Example querySelectorAll()</h4>
<ul>
 <li class='sites'>CoursesWeb.net</li>
 <li class='sites'>MarPlo.net</li>
 <li>GamV.eu.net</li>
</ul>
<div id='dv1'>
 Web Development courses - <span class='note'>querySelector and querySelectorAll</span>
</div>
<p style='background:#fbfbb0;'>The JS script gets an array with the LI tags with class='sites' and the tag with class='note' from #dv1 (css selector: '<b>li.sites, #dv1 .note</b>' ).<br>
If you click the button, it displays their content at #resp.</p>
<button id='btn1'>Click</button>
<blockquote id='resp'>#resp</blockquote>

<script>
// gets all the LI tags with class='sites', and the tags with class='note' in element with id='dv1'
var elms = document.querySelectorAll('li.sites, #dv1 .note');
var btn = document.querySelector('#btn1');
btn.addEventListener('click', (ev)=>{
 var re ='';

//traverse the elms array, and adds in re the content of each element
 for(var i=0; i<elms.length; i++) {
 re += elms[i].innerHTML +'<br>';
 }

 //adds the string in #resp
 document.getElementById('resp').innerHTML = re;
});
</script>

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 an array 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 input field.
<p style='background:#fbfbb0;'>The JS script apply querySelectorAll() to gets the elements within the tag with id 'sites'.<br>
 - When the mouse is over the next links, the address from 'href' it is added in the text field.</p>
Adresa URL: <input type='text' id='txt1' />
<ul id='sites'>
 <li><a href='//coursesweb.net/javascript' title='JavaScript Course'>JavaScript Course</a></li>
 <li><a href='//gamv.eu/' title='Flash Games'>Flash Games</a></li>
</ul>

<script>
var txt1 = document.getElementById('txt1');

// gets A tags in LI added in element with id='idata'
var elms = document.getElementById('sites').querySelectorAll('li a');

//registers mouseenter to each element in elms array
for(var i=0; i<elms.length; i++){
 elms[i].addEventListener('mouseenter', (ev)=>{
 txt1.value = ev.target.href;
 });
}
</script>

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which attribute indicates that an input field must be filled out before submitting?
required="required" autofocus="autofocus" placeholder="text"
<input type="text" name="name1" required="required" />
Which CSS method increases or decreases the size of the HTML element (including its content)?
translate() scale() skew()
#some_id:hover {
  transform: scale(2, 1.5);
  -ms-transform: scale(2, 1.5);    /* IE 9 */
  -moz-transform: scale(2, 1.5);   /* Firefox */
}
Click on the Date object method that returns the day of the month.
setDate() getMonth() getDate()
var rightnow = new Date();
var day = rightnow.getDate();
alert(day);
Which function is used to upload a file on server?
is_file() move_uploaded_file() fopen()
if(move_uploaded_file($_FILES["field_name"]["tmp_name"], "dir/file_name")) {
  echo "The file succesfully uploaded";
}
querySelector and querySelectorAll

Last accessed pages

  1. JQZoom Image Magnifier (9940)
  2. SHA512 Encrypt hash in JavaScript (10932)
  3. Add Pause in JavaScript script (9962)
  4. Redirects (758)
  5. PHP PDO - exec (INSERT, UPDATE, DELETE) MySQL (42971)

Popular pages this month

  1. Insert, Select and Update NULL value in MySQL (417)
  2. Read Excel file data in PHP - PhpExcelReader (331)
  3. PhpSpreadsheet - Read, Write Excel and LibreOffice Calc files (258)
  4. PHP getElementById and getElementsByTagName (210)
  5. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (199)