如何找到jQuery中是否存在具有特定ID的div?

2022-08-30 00:12:17

我有一个函数,可以在单击时将a附加到元素。该函数获取单击的元素的文本,并将其分配给名为 的变量。然后,该变量用作追加元素的 。<div>name<div>id

在追加元素之前,我需要查看是否已经存在一个,但我不知道如何找到它。<div>idname

这是我的代码:

$("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');
});

这似乎很简单,但我收到错误“搜索类名时文件意外结束”。我不知道这意味着什么。

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>");
}

更重要的是,如果我将其关闭,我希望能够删除此元素,然后应该从文档中删除,但不这样做。div id [name].remove()

这是代码:

$(".mini-close").live('click', function(){
  $(this).parent().remove();
});

我作为子函数添加到 append 函数中,因此有一种方法可以在需要时关闭追加函数。单击并尝试再次单击相同的名称后,它仍然可以找到并返回我的语句的第一部分。.mini-close.labels<div>.mini-closeli.friendsdiv id [name]if


答案 1

您可以在选择器后使用 .length 来查看它是否与任何元素匹配,如下所示:

if($("#" + name).length == 0) {
  //it doesn't exist
}

完整版:

$("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');
  }
});

或者,此部分的非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');
  }
});

答案 2

尼克的回答就敲定了。你也可以直接使用getElementById的返回值作为你的条件,而不是将其与null进行比较(无论哪种方式都有效,但我个人发现这种风格更具可读性):

if (document.getElementById(name)) {
  alert('this record already exists');
} else {
  // do stuff
}