Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
495 views
in Technique[技术] by (71.8m points)

selection - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...