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

后端 未结 10 1317
我在风中等你
我在风中等你 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:07

    You can handle it in different ways,

    Objective is to check if the div exist then execute the code. Simple.

    Condition:

    $('#myDiv').length
    

    Note:

    #myDiv -> < div id='myDiv' > 
    .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

    // 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("
    " + name + "
    "); } // Statement 1 if ($('#'+ name).length){ // if 0 then false ; if not 0 then true $("div#page-content div#chatbar").append("
    " + name + "
    "); } // Statement 2 if(!$('#'+ name).length){ // ! Means Not. So if it 0 not then [0 not is 1] $("div#page-content div#chatbar").append("
    " + name + "
    "); } // Statement 3 if ($('#'+ name).length > 0 ) { $("div#page-content div#chatbar").append("
    " + name + "
    "); } // Statement 4 if ($('#'+ name).length !== 0 ) { // length not equal to 0 which mean exist. $("div#page-content div#chatbar").append("
    " + name + "
    "); }

提交回复
热议问题