If jQuery selector return no element, then what will happen. For example, I execute the following:
$('.myclass').show();
Based on my test, it seems jQuery will check whether $('.myclass') is null, if not, then it will execute .show(), otherwise, nothing happens.
I translate the above codeline to JavaScript, as below:
document.querySelector('.myclass').style.display = 'block';
But this time if document.querySelector('.myclass') return null, there will be an error.
CodePudding user response:
If there are no matching elements, it does nothing.
If there are any matching elements, it will show all such matching elements.
It's somewhat similar to the following:
for (const elm of document.querySelectorAll(selector)) {
elm.style.display = 'block';
}
If there are no elements matching whatever selector
is, nothing happens, but no error is thrown.
Similarly, if there are no elements matching .myclass
, no iteration happens, and nothing changes in the DOM, and no error is thrown.