Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: querySelector Null vs querySelector

What is the main difference between these two methods of referencing?

What are the benefits of using one or the other? Also what kind of usage-case would they each be best suited to?

var selection = document.querySelector('.selector') !== null;

var selection = document.querySelector('.selector');

Is the former solely for browser legacy support?

like image 341
user3143218 Avatar asked Apr 10 '14 11:04

user3143218


People also ask

How do I check if a querySelector is null?

To check if an element does not exist in the DOM: Use the getElementById or querySelector methods to select the element. Check if the stored value is equal to null . If the value is equal to null , the element does not exist in the DOM.

Can querySelector return null?

querySelector() The Document method querySelector() returns the first Element within the document that matches the specified selector, or group of selectors. If no matches are found, null is returned.

What is the difference between querySelector and getElementsByClassName?

About the differences, there is an important one in the results between querySelectorAll and getElementsByClassName : the return value is different. querySelectorAll will return a static collection, while getElementsByClassName returns a live collection.

Is querySelector better than getElementById?

getElementById is better supported than querySelector . querySelector is better supported than getElementsByClassName but querySelector gives you a static node list while getElementsByClassName gives you a live node list. You need to pick the appropriate tool for any given task.


1 Answers

The first one gets the reference and checks if the element exists, and saves this status as a boolean value in the variable. If the element exists, the variable contains true otherwise false.

You would use the first one if you only want to know if the element exists, but don't need the reference to it.

Example:

var selection = document.querySelector('.selector') !== null;
if (selection) {
  alert('The element exists in the page.');
} else {
  alert('The element does not exists in the page.');
}

The second one gets the reference and stores in the variable, but doesn't check if the element exists. If the element exists, the variable contains the reference to the element, otherwise the variable contains null.

You would use the second one if you need the reference to the element. If it's possible that the element doesn't exist in the page, you should check if the variable contains null before you try to do something with the reference.

Example:

var selection = document.querySelector('.selector');
if (selection !== null) {
  alert('I have a reference to a ' + selection.tagName + ' element.');
} else {
  alert('The element does not exists in the page.');
}
like image 141
Guffa Avatar answered Sep 18 '22 22:09

Guffa