How to find if div with specific id exists in jQuery?

后端 未结 10 1180
我在风中等你
我在风中等你 2020-11-28 17:51

I’ve got a function that appends a

to an element on click. The function gets the text of the clicked element and assigns it to a variable called
相关标签:
10条回答
  • 2020-11-28 18:21

    Here is the jQuery function I use:

    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 .

    0 讨论(0)
  • 2020-11-28 18:27

    You can use .length after the selector to see if it matched any elements, like this:

    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):

    $("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');
      }
    });
    
    0 讨论(0)
  • 2020-11-28 18:31

    You can check by using jquery simply like this:

    if($('#divId').length!==0){
          Your Code Here
    }
    
    0 讨论(0)
  • 2020-11-28 18:34

    put the id you want to check in jquery is method.

    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
    }
    
    0 讨论(0)
提交回复
热议问题