Javascript 如何查找具有特定 id 的 div 是否存在于 jQuery 中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3373763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find if div with specific id exists in jQuery?
提问by sadmicrowave
I've got a function that appends a <div>to an element on click. The function gets the text of the clicked element and assigns it to a variable called name. That variable is then used as the <div>idof the appended element.
我有一个函数,<div>可以在单击时将 a 附加到元素。该函数获取单击元素的文本并将其分配给名为 的变量name。然后将该变量用作<div>id附加元素的 。
I need to see if a <div>idwith namealready exists before I append the element but I don't know how to find this.
在添加元素之前,我需要查看<div>idwith 是否name已经存在,但我不知道如何找到它。
Here is my code:
这是我的代码:
$("li.friend").live('click', function() {
name = $(this).text();
// if-statement checking for existence of <div> should go here
// If <div> does not exist, then append element
$("div#chatbar").append("<div class='labels'><div id='" + name + "' style='display:none;'></div>" + name + "</div>");
// Else
alert('this record already exists');
});
This seems pretty straightforward but I'm getting the error “Unexpected end of file while searching for class name”. I have no clue what that means.
这看起来很简单,但我收到错误“搜索类名时出现意外的文件结尾”。我不知道这意味着什么。
if (document.getElementById(name)) {
$("div#" + name).css({bottom: '30px'});
} else {
$("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
}
What's more is that I want to be able to delete this element if I close it out which should then remove the div id [name]from the document but .remove()does not do this.
更重要的是,如果我关闭它,我希望能够删除这个元素,然后应该div id [name]从文档中删除它,但.remove()不这样做。
Here is the code for that:
这是代码:
$(".mini-close").live('click', function(){
$(this).parent().remove();
});
I added .mini-closeto the append function as a child of .labelsso there was a way to close out of the appended <div>if needed. After clicking .mini-closeand attempting to click the same name again from li.friendsit still finds the div id [name]and returns the first part of my ifstatement.
我添加.mini-close到 append 函数作为一个孩子,.labels所以有一种方法可以<div>在需要时关闭附加。单击.mini-close并尝试再次单击相同的名称后,li.friends它仍然会找到div id [name]并返回我if语句的第一部分。
回答by Nick Craver
You can use .lengthafter the selector to see if it matched any elements, like this:
您可以.length在选择器之后使用来查看它是否匹配任何元素,如下所示:
if($("#" + name).length == 0) {
//it doesn't exist
}
The full version:
完整版:
$("li.friend").live('click', function(){
name = $(this).text();
if($("#" + name).length == 0) {
$("div#chatbar").append("<div class='labels'><div id='" + name + "' style='display:none;'></div>" + name + "</div>");
} else {
alert('this record already exists');
}
});
Or, the non-jQuery version for this part (since it's an ID):
或者,这部分的非 jQuery 版本(因为它是一个 ID):
$("li.friend").live('click', function(){
name = $(this).text();
if(document.getElementById(name) == null) {
$("div#chatbar").append("<div class='labels'><div id='" + name + "' style='display:none;'></div>" + name + "</div>");
} else {
alert('this record already exists');
}
});
回答by philo
Nick's answer nails it. You could also use the return value of getElementById directly as your condition, rather than comparing it to null (either way works, but I personally find this style a little more readable):
尼克的回答说明了这一点。您也可以直接使用 getElementById 的返回值作为您的条件,而不是将其与 null 进行比较(无论哪种方式都有效,但我个人认为这种样式更具可读性):
if (document.getElementById(name)) {
alert('this record already exists');
} else {
// do stuff
}
回答by Tapan kumar
Try to check the length of the selector, if it returns you something then the element must exists else not.
尝试检查选择器的长度,如果它返回一些东西,那么该元素必须存在,否则不存在。
if( $('#selector').length ) // use this if you are using id to check
{
// it exists
}
if( $('.selector').length ) // use this if you are using class to check
{
// it exists
}
Use the first if condition for id and the 2nd one for class.
id 使用第一个 if 条件,class 使用第二个 if 条件。
回答by Kareem
if($("#id").length) /*exists*/
if(!$("#id").length) /*doesn't exist*/
回答by Sanjib Debnath
if ( $( "#myDiv" ).length ) {
//id id ( "#myDiv" ) is exist this will perform
$( "#myDiv" ).show();
}
Another shorthand way:
另一种速记方式:
$( "#myDiv" ).length && $( "#myDiv" ).show();
回答by Hariprasath
You can check by using jquery simply like this:
您可以像这样使用 jquery 进行检查:
if($('#divId').length!==0){
Your Code Here
}
回答by rckd
The most simple way is..
最简单的方法是..
if(window["myId"]){
// ..
}
This is also part of HTML5 specs: https://www.w3.org/TR/html5/single-page.html#accessing-other-browsing-contexts#named-access-on-the-window-object
这也是 HTML5 规范的一部分:https: //www.w3.org/TR/html5/single-page.html#accessing-other-browsing-contexts#named-access-on-the-window-object
window[name]
Returns the indicated element or collection of elements.
回答by Sahan
Here is the jQuery function I use:
这是我使用的 jQuery 函数:
function isExists(var elemId){
return jQuery('#'+elemId).length > 0;
}
This will return a boolean value. If element exists, it returns true.
If you want to select element by class name, just replace #with .
这将返回一个布尔值。如果元素存在,则返回真。如果要按类名选择元素,只需替换#为.
回答by Ad Kahn
You can handle it in different ways,
你可以用不同的方式处理它,
Objectiveis to check if the div exist then execute the code. Simple.
目标是检查 div 是否存在,然后执行代码。简单的。
Condition:
健康)状况:
$('#myDiv').length
Note:
笔记:
#myDiv -> < div id='myDiv' > <br>
.myDiv -> < div class='myDiv' >
This will return a number every time it is executed so if there is no div it will give a Zero [0], and as we no 0 can be represented as false in binary so you can use it in if statement. And you can you use it as a comparison with a none number. while any there are three statement given below
这将在每次执行时返回一个数字,因此如果没有 div,它将给出零 [0],并且由于我们没有 0 可以在二进制中表示为 false,因此您可以在 if 语句中使用它。您可以将其用作与 none 数字的比较。而任何有下面给出的三个陈述
// Statement 0
// jQuery/Ajax has replace [ document.getElementById with $ sign ] and etc
// if you don't want to use jQuery/ajax
if (document.getElementById(name)) {
$("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
}
// Statement 1
if ($('#'+ name).length){ // if 0 then false ; if not 0 then true
$("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
}
// Statement 2
if(!$('#'+ name).length){ // ! Means Not. So if it 0 not then [0 not is 1]
$("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
}
// Statement 3
if ($('#'+ name).length > 0 ) {
$("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
}
// Statement 4
if ($('#'+ name).length !== 0 ) { // length not equal to 0 which mean exist.
$("div#page-content div#chatbar").append("<div class='labels'>" + name + "</div><div id='" + name + "'></div>");
}
回答by bhavya_w
put the id you want to check in jquery is method.
把你想检查的 id 放在 jquery is 方法中。
var idcheck = $("selector").is("#id");
if(idcheck){ // if the selector contains particular id
// your code if particular Id is there
}
else{
// your code if particular Id is NOT there
}

