valerio0999 valerio0999 - 2 months ago 11
HTML Question

jquery has in if statement triggering in any case

I'm using jquery

.has()
to check if a
div
has an
ul
inside it. it's in a
if
statement but it fires in any case, even if the
div
doesn't have the
ul
inside it:



if ($(".cs-error").has("ul")) {
alert("it has a UL")
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cs-error">

</div>





what am i missing? I didn't try much because well.. I'm supposed to do this simple thing and I couldn't find a better way to do it. I already use .has() in other circumstances and it always worked

Answer

$(".cs-error").has("ul") will give you a jQuery object nonetheless - but an empty one.

So you should check if there was at least one element found:

if ($(".cs-error").has("ul").length) {
Comments