Search code examples
javascriptdomclone

Clone element in a DOM and change the attribute while reusing it in javascript


My code is given below

;(function(window){

    var description_window= document.querySelector('.mg_post_description');

    var $headings= document.querySelectorAll('.mg_blog_main_content h3');

    for (var i = $headings.length - 1; i >= 0; i--) {

        description_window.append($headings[i].cloneNode(true));
    };

})(window);

Can I change the h3 collected from the 'blog_main_contents' to 'p' tags in the target div.

Thanks and regards


Solution

  • You can iterate through h3's child nodes and append it to new paragraph element:

    var paragraph = document.createElement('p');
    var headingChildren = $headings[i].cloneNode(true).childNodes;
    for (var j = 0; j < headingChildren.length; j++) {
      paragraph.appendChild(headingChildren[j]);
    }
    description_window.append(paragraph);