Maarten Wolfsen Maarten Wolfsen - 7 months ago 14
Javascript Question

.has() function not working in if statement (jQuery)

I have this code:

if ($('.workflow-item:eq(0)').has(".tube-wrapper")) {
itemresT = 0;
console.log('0 has tube')
} else if ($('.workflow-item').eq(1).has(".tube-wrapper")) {
itemResT = 1;
console.log('1 has tube')
} else if ($('.workflow-item').eq(2).has(".tube-wrapper")) {
itemResT = 2;
console.log('2 has tube')
} else if ($('.workflow-item').eq(3).has(".tube-wrapper")) {
itemResT = 3;
console.log('3 has tube')
} else {}


It's quite easy, it checks the four
.workflow-item
if they contain the element
.tube-wrapper
.

In my case,
.workflow-item
number 3 contains the
.tube-wrapper
, so it should return '2 has tube'. But, it returns '0 has tube' everytime. Even when I put the
.tube-wrapper
in
.workflow-item number 4
.

Answer

If conditions will be always true, since has() returns jQuery object and it will be always true since defined variable accepted as truth value. You can use length property of it or size() method.

if($('.workflow-item').eq(1).has(".tube-wrapper").length)


Or you can use is() with :has() selector

if($('.workflow-item').eq(1).is(':has(.tube-wrapper)'))
Comments