简体   繁体   English

如何测试jQuery中页面上是否存在具有特定ID的元素?

[英]How do I test if an element with a certain ID exists on a page in jQuery?

In jQuery, I have written a piece of code that appears on every page of my website. 在jQuery中,我编写了一段代码,出现在我网站的每一页上。

var d = $('#someElement').offset().top;

However, not every page on my website has an element with an ID of "someElement". 但是,并非我网站上的每个页面都有一个ID为“someElement”的元素。 Unfortunately, on these pages that lack such an element, no jQuery code works. 不幸的是,在缺少这种元素的这些页面上,没有jQuery代码可以工作。

To solve this problem, I want to test if an element on the page indeed has the ID of "someElement" and then only run the code snippet above if there is. 为了解决这个问题,我想测试页面上的元素是否确实具有“someElement”ID,然后只运行上面的代码片段。

How do I perform this test? 我该如何进行这项测试? Will this test solve the problem? 这个测试会解决这个问题吗? Thank you. 谢谢。

$('#someElement').length如果元素存在,则$('#someElement').length将返回1 ,否则返回0

Check the length of the jQuery object. 检查jQuery对象的长度。

var element = $('#someElement');
if (element.length) {
    var element_top = element.offset().top;
}

使用if statemtent: if ($('#someElement').length) { do something }

try this: 尝试这个:

if($('#someElement').length>0){
   var d = $('#someElement').offset().top;
}

Just an alternative way of solving it: You can run var d = $('#someElement').offset() without causing an error (it will just return null), even if the element does not exist. 只是另一种解决方法:你可以运行var d = $('#someElement').offset()而不会导致错误(它只会返回null),即使该元素不存在。 So try: 所以尝试:

var d = $('#someElement').offset();
if (d) {
    d = d.top;
}

Do not use jQuery for that! 不要使用jQuery! Use getElementById , since if the element is not in the DOM, the result will be null . 使用getElementById ,因为如果元素不在DOM中,则结果为null

if (document.getElementById("someElement")) {

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM