Each of the following if statements works perfectly as long as the other if statement isn’t present.
I don’t understand why having both if statements causes the function not to work.
I’ve tried so many variations but can’t figure it out.
This is the code:
$("a").click(function(event){
event.preventDefault();
let lItem = document.querySelectorAll(".listing-item");
let mItem = document.querySelectorAll(".menu-item");
let destination = $(this).attr("href");
if ( $(this).parent(lItem) ) {
tlUp.tweenTo(0, {
onComplete: () => {
window.location = destination;
}
});
}
if ( $(this).parent(mItem) ) {
tlMenu.tweenTo(0, {
onComplete: () => {
window.location = destination;
}
});
}
});
2
Answers
The jQuery
.parent()
method expects a string or nothing for argument, you are passing an instance ofNodeList
, that is equivalent to passing nothing. For this reason both your conditions are true, because$(this)
always has a parent (since it is not document root).If you want to check whether an element’s parent belongs to certain groups defined by
lItem
ormItem
, you should use a different approach. A correct way to do this is by using jQuery’s.closest()
method, which accepts a string selector and traverses up the DOM to find the first ancestor that matches the provided selector.For example:
Or, if you want to check if element parent has that specific class, you could use this form:
In this last example
.parent()
is used to select direct parent of current element, then.is(...)
is used to check if that parent element has that specific class.Based on your given code, it seems like you want to check that if an immediate parent of
<a>
has a specific class (eitherlisting-item
ormenu-item
) then based on that perform a different action.In that case, you need to modify your code like the below: (by using
.hasClass()
along with.parent()
)References:
.parent()
.hasClass()