简体   繁体   中英

Check if an element exists in the DOM

The following snippet is not working for me. Basically I want to check if there is an input element with the name "documents[]" and the value item.id and return void.

I thought this line would do it: $("input [name='documents[]'][value='"+item.id+"'") != false .

However the statement returns true every time. I have looked at the documentation for the jQuery constructor and it doesn't mention anything about returning false if no element is found for the selector.

How can I tell if the selector doesn't match any elements?

    $.ajax({
        url:'/myid/documents/json_get_documents/'+request.term,
        dataType:"json",
        success: function(data) {
            response($.map(data, function(item){
                if($("input [name='documents[]'][value='"+item.id+"'") != false) {
                    return; //This item has already been added, don't show in autocompete
                }
                return {
                    label: '<span class="file">'+item.title+'</span>',
                    id: item.id,
                    value: 'Search by title'
                }
            }))
        }
    });
$("input [name='documents[]'][value='"+item.id+"'"]).length

This property will have a length value greater than zero if that element is available in the DOM. You see, when you select an element using jquery's selector, it creates a special array(or you could say, a jquery object) with that element. If multiple elements can be selected with that selector, then the array will contain all of them and if no element matches that selector, the array will have nothing, and in that case it's length property will be zero.

Hope that helps.

You can use .length . $('lol').length returns 0 while $('body').length returns 1.

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