I have the following html:
<div class="switch has-switch">
<div class="switch-animate switch-on">
<input id="completed" type="checkbox" data-toggle="switch" data-shopify="data shopify" data-order="order number" class="ct-primary completed" value="0"><span class="switch-left">DONE</span>
<label for="completed"> </label><span class="switch-right">NOT</span></div>
</div>
The above html is repeated 8 times in an html page I have. I’m trying to check if the class input is present.
I have an array like so:
const tags = ['completed', 'printing', 'proofing'];
I then try to loop over the tags and check each element that has .switch
function switches(tags) {
tags.forEach((item) => {
$('.switch').each(function () {
const thisEl = $( this ).find('.switch-animate');
if(thisEl.has(`#${item}`)) {
thisEl.removeClass( 'switch-off' );
thisEl.addClass( 'switch-on' );
}
});
});
}
My problem is that it’s not working meaning when has is NOT present it still gives does not give me a false. I would expect a false if thisEl didn’t have the item.
Any idea what I’m doing wrong?
2
Answers
The problem is that
has
returns a jquery object for chaining. And objects are always truthy, so yourif
will always run the true branch.Why? Because the purpose of
has
is to reduce a set of selected elements to a smaller set that matches the query.See: https://api.jquery.com/has/
What you want is something that returns true or false like
$.contains
see: https://api.jquery.com/jQuery.contains/
.has()
will return object (As mentioned by @Fred Stark in another answer). You should be using.length
of returned object.