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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With