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.
- 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
1 Answer
Reset to default 11Handling 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
版权声明:本文标题:javascript - How to silently fail querySelector() like jQuery() if element does not exists - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742064553a2418753.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论