Search code examples
javascriptvariablescloneappendchild

How do you clone, update & append a variable using JavaScript


I'm trying to create a variable with the value within '.comments' then prepend the word 'Read all' in front of '4 comments'. Finally, append the new variable to '#comments'.

Manage to write something but it's moving the existing object instead of creating a new object with the value of the existing one.

Some code below

<script type="text/javascript">
var commentsLink = document.querySelector('.story .comments a'),    
    commentsSubmit = document.querySelector('#comments .form-item-submit');
commentsLink.innerHTML = 'Read all ' + commentsLink.innerHTML;
commentsLink.className += 'readComments';
commentsSubmit.appendChild(commentsLink);
</script>

<div class="story">
     <div class="comments">
           <a href="http://foo.com">4 comments</a>
     </div>
</div>
<div id="comments">
     <div class="form-item-submit">Submit</div>
</div>

Desired result:

<div class="story">
     <div class="comments">
           <a href="http://foo.com">4 comments</a>
     </div>
</div>
<div id="comments">
     <div class="form-item-submit">Submit</div>
     <a href="http://foo.com" class="readComments">Read all 4 comments</a>
</div>

Can anyone shed some light on this? No Jquery please.


Solution

    1. To clone elements, use cloneNode. To copy the text contents as well, use cloneNode(true).
    2. You want the cloned link to be appended at the parent element of the submit div, not inside the submit div itself.

    http://jsfiddle.net/eDGwj/

    var commentsLink = document.querySelector('.story .comments a').cloneNode(true),
        commentsSubmit = document.querySelector('#comments .form-item-submit');
    
    commentsLink.innerHTML = 'Read all ' + commentsLink.innerHTML;
    commentsLink.className += 'readComments';
    
    commentsSubmit.parentNode.appendChild(commentsLink);