Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to check exist value attribute with jQuery

Tags:

html

jquery

I want to check value of attribute html tag and if that element not exist with value of attribute append certain element in my html.

for example I have many li tags like this:

<ul id="friend-list">
    <li id="1"></li>
    <li id="2"></li>
    <li id="3"></li>
    <li id="4"></li>
    <li id="5"></li>
    <li id="6"></li>
</ul>

I want when click on any li run this jQuery code and append one element :

append element :

var conversation ='<div class="conversation stream" id='+ conversationID +'><div class="timeline"><ul class="all-msg"><li class="me typing"><div id="chat-text" contenteditable="true"></div><div id="upload-f"></div><div id="upload-p"></div><div id="chat-arrow"></div></li></ul></div></div>';
$('body').append(conversation);

jQuery code:

$(document).on('click','#friend-list li',function(){
    var getID = $(this).attr('id');
    var conversationID = 'Conver-' + getID;
    console.log(conversationID);


    if(/* don't exist element with attribute and value*/){
        // append that element

        var conversation ='<div class="conversation stream" id='+ conversationID +'><div class="timeline"><ul class="all-msg"><li class="me typing"><div id="chat-text" contenteditable="true"></div><div id="upload-f"></div><div id="upload-p"></div><div id="chat-arrow"></div></li></ul></div></div>';
        $('body').append(conversation);
    }

});

so I want first check exist that I want append it. if this element not exist so append this Otherwise don't append this.

thanks a lot guys.

like image 709
Mohammad Kasiri Avatar asked Mar 23 '23 17:03

Mohammad Kasiri


1 Answers

One solution is to check whether an element with the converssationID exists

$(document).on('click','#friend-list li',function(){
    var getID = $(this).attr('id');
    var conversationID = 'Conver-' + getID;
    console.log(conversationID);

    if(!$('#' + conversationID).length) {   
        var conversation ='<div class="conversation stream" id='+ conversationID +'><div class="timeline"><ul class="all-msg"><li class="me typing"><div id="chat-text" contenteditable="true"></div><div id="upload-f"></div><div id="upload-p"></div><div id="chat-arrow"></div></li></ul></div></div>';
        $('body').append(conversation);
    }
});

Demo: Fiddle

Note: You are appending elements with id chat-text and upload-f to every conversation which is invalid since ID should be unique in a document

like image 185
Arun P Johny Avatar answered Mar 25 '23 06:03

Arun P Johny