admin管理员组

文章数量:1320661

I can't get this thing right.
Why jQuery() outputs an object by default? And is there some way to achieve same result with JavaScript?

jQuery('#configurator-material')
init [section#configurator-material.section, context: document, selector: "#configurator-material"]

document.querySelector('#configurator-material');
<section id=​"configurator-material" class=​"section" ng-controller=​"materialCtrl as material">​…​</section>​

document.querySelectorAll('#configurator-material');
NodeList [section#configurator-material.section]

In general my problem is that at some point I have this line:

jQuery('#myid').addClass('myclass');

im trying to replace it with JS like this:

document.querySelector('#myid').classList.add('myclass');

I thought that it should be fine and without errors,
but i'm getting "Cannot read property 'classList' of null" on the JS variant if a specific element does not exists on the page.

I can't get this thing right.
Why jQuery() outputs an object by default? And is there some way to achieve same result with JavaScript?

jQuery('#configurator-material')
init [section#configurator-material.section, context: document, selector: "#configurator-material"]

document.querySelector('#configurator-material');
<section id=​"configurator-material" class=​"section" ng-controller=​"materialCtrl as material">​…​</section>​

document.querySelectorAll('#configurator-material');
NodeList [section#configurator-material.section]

In general my problem is that at some point I have this line:

jQuery('#myid').addClass('myclass');

im trying to replace it with JS like this:

document.querySelector('#myid').classList.add('myclass');

I thought that it should be fine and without errors,
but i'm getting "Cannot read property 'classList' of null" on the JS variant if a specific element does not exists on the page.

Share Improve this question edited Jul 22, 2020 at 0:15 Roko C. Buljan 207k41 gold badges327 silver badges339 bronze badges asked Jul 21, 2020 at 20:53 AlexAlex 711 silver badge9 bronze badges 8
  • jQuery returns the selected elements wrapped in a jQuery special object (defined by jQuery itself), you won't have the same unless you create a similar object wrapping the elements – arieljuod Commented Jul 21, 2020 at 20:57
  • 3 The entire point of jQuery is that it returns an object so you can call methods on it to interact with the element(s) in the DOM. I'm not sure what the problem is, or the point of the question. – Rory McCrossan Commented Jul 21, 2020 at 20:57
  • What does console.log() says if you try to get that element? Are you sure DOM is read and ready? Remember, Undeferred scripts should go before the closing </body> tag, not inside head. – Roko C. Buljan Commented Jul 21, 2020 at 21:12
  • @RokoC.Buljan jQuery('#myid') - console outputs = object. So no problem. document.querySelector('#myid') - console outputs = 'null'.. – Alex Commented Jul 21, 2020 at 21:15
  • 2 Because your vanilla syntax is wrong. You have to check if the target exists applying it. document.querySelector('#myid')?.classList.add('myclass'); – Jens Ingels Commented Jul 22, 2020 at 0:23
 |  Show 3 more ments

1 Answer 1

Reset to default 11

Handling non existent Elements

Internally the jQuery library conditionally handles non existent elements - failing silently without error.
Take for example a $("#nonExistent"), even if the Element is not retrieved in the DOM, the returned value will still be a jQuery Object instance - with all its constructor methods available, like .addClass() etc.

In contrast, JavaScript's .querySelector() returns an Element Object, but if the element is not found — the primitive null is returned.
JavaScript will break your code if you try to access properties of non-Object. Just like manually writing null.classList will throw an error:

Uncaught TypeError: Cannot read properties of null

Use JavaScript Optional Chaining .?

The simplest way to emulate the similar non-erratic behavior is to use the Optional Chaining operator .?

// jQuery
$("#notExistent").addClass("red"); // No errors

// JavaScript
document.querySelector("#notExistent")?.classList.add("red"); // No errors
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Use Babel if you need to pile your ES6 code in order to support older browsers like i.e: IE (Internet Explorer), or just use an if statement:

// JavaScript
const EL_notExistent = document.querySelector("#notExistent");
if (EL_notExistent) EL_notExistent.classList.add("red"); // No errors

本文标签: javascriptHow to silently fail querySelector() like jQuery() if element does not existsStack Overflow