Maarten Wolfsen Maarten Wolfsen - 1 year ago 64
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
if they contain the element

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

Answer Source

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.


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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download