简体   繁体   English

检查DOM中是否存在元素

[英]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. 基本上,我想检查是否存在名称为“ documents []”且值为item.id的输入元素,并返回void。

I thought this line would do it: $("input [name='documents[]'][value='"+item.id+"'") != false . 我以为这行代码可以做到: $("input [name='documents[]'][value='"+item.id+"'") != false

However the statement returns true every time. 但是,该语句每次都返回true。 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. 我已经看过jQuery构造函数的文档,并且在没有为选择器找到任何元素的情况下,它没有提及关于返回false的任何内容。

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. 如果该元素在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. 您会看到,当使用jquery的选择器选择一个元素时,它会使用该元素创建一个特殊的数组(或者可以说是一个jquery对象)。 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. 如果可以使用该选择器选择多个元素,则数组将包含所有元素,并且如果没有元素与该选择器匹配,则该数组将没有任何内容,在这种情况下,其length属性将为零。

Hope that helps. 希望能有所帮助。

You can use .length . 您可以使用.length $('lol').length returns 0 while $('body').length returns 1. $('lol').length返回0$('body').length返回1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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