开发者

jQuery check for adjacent selector

开发者 https://www.devze.com 2023-02-22 21:08 出处:网络
I am trying to check for the existence of an adjacent (next) selector but I am clearly writing it incorrectly...

I am trying to check for the existence of an adjacent (next) selector but I am clearly writing it incorrectly...

My HTML

<div id="container">
<div class="about"></div>
&开发者_StackOverflow中文版lt;div class="related"></div>
</div>

My jQuery:

jQuery(document).ready(function() {
console.log(jQuery("div.about").next().hasClass(".related"));
    if (jQuery("div.about").next().hasClass(".related"))
    {
        console.log("do something");
    }
});

My first console.log shows FALSE and my second isn't showing at all...


It should be without the dot. hasClass does not take a selector, but just the name of the class:

jQuery("div.about").next().hasClass("related")

Or alternatively:

jQuery("div.about").next('.related').length > 0


Maybe try this instead.

jQuery("div.about").next().hasClass("related");

Just drop the .


You don't need the . in your .hasClass selectors

jQuery(document).ready(function() {
    console.log(jQuery("div.about").next().hasClass("related"));
    if (jQuery("div.about").next().hasClass("related")) {
        console.log("do something");
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消