简体   繁体   中英

check for element presence in jquery

I have a page in which i have to search for presence of element depending on first input in the first form only

<input type="text" /><!-- first input -->
<button></button>
<div>
    <form><input value="3" /></form> <!-- first form -->
    <form><input value="3" /></form>
</div>

and script

$("button").click(function()
{
    if( $(this).next().children("form").first().has("input[value='" + $(this).prev().val() + "']") )
        alert("Present");
    else
        alert("Absent");
});

But it's not working

You can check the presence of an element by checking the length of the collection a query returns:

For example, if i were to check if i had forms:

var forms = $('form').length //0 if none, at least 1 if any

The problem is that the .has() method doesn't return a boolean, it returns a jQuery object, specifically it "constructs a new jQuery object from a subset of the matching elements". You need to check the length of that object to see if any elements matched:

if($(this).next().children("form").first()
           .has("input[value='"+$(this).prev().val()+"']").length != 0)

Demo: http://jsfiddle.net/mmQHB/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM