Kendall Weihe Kendall Weihe - 4 months ago 34
HTML Question

JQuery clone li+children, update text (in child tag), and append

I have some pretty cool CSS that I want to reuse in a

<ul>
. I want to clone an existing
<li>
(so that I can reuse CSS), update a
<p>
field, and then append it to the end of the
<ul>
.

I know I can do something like this to find...

var temp = $(".chatboxcontent").find('li');
console.log(temp);


And then I can use
.clone
like so... (is this correct?)

var temp2 = temp.clone


So then I need to delete a
<p>
and then insert my own
<p>


The HTML element looks like this...

<div class="chatboxcontent">
<li class="current-user-message">
<div class="avatar">
<img src="http://placehold.it/50x50">
</div>
<div class="chatboxmessagecontent">
<p>test</p>
<time datetime="2016-07-28 16:45:20 UTC" title="28 Jul 2016 at 04:45PM">
16:45 PM
</time>
</div>
</li>
<li class="current-user-message">
<div class="avatar">
<img src="http://placehold.it/50x50">
</div>
<div class="chatboxmessagecontent">
<p>test</p>

...and so on


I need to delete then insert text in the
<p>test</p>
element and then append it to the
class="chatboxcontent"


I'm thinking something like this...

var message_li = $(".chatboxcontent").find('li').clone();
$(message_li).innerHTML("p") = data.text;
$(".chatboxcontent").append(message_li);


From the above I get
$(...).innerHTML is not a function
. So how do I delete the element and then insert it?

Is there a better way to implement this?

Answer

You can try this:

$(".chatboxcontent") //Select the conatiner
.find('li:first') //Find the first 'li' element
.clone() //then clone it
.find('p') //Find the 'p' tag inside the cloned element
.html(data.text) // change the html of the 'p' tag
.end() // Return to the cloned 'li' with the 'p' tag changed
.appendTo('.chatboxcontent'); // append the cloned 'li' to the conatiner

Demo: https://jsfiddle.net/iRbouh/x4h69939/

I hope this will help.

Comments