Mathieu
Mathieu

Reputation: 761

Wrap first div of a div

I want to wrap or replace the first div and p which is in a div called entry-content :

var outer = document.getElementById(".entry-content div");
outer.innerHTML = "<div id='wrap'>"+outer.innerHTML+"</div>"

and

var outer = document.getElementById(".entry-content p");
outer.innerHTML = "<script type='text/javascript'>window.location = '"+outer.innerHTML+"'</script>"

Output (wrap):

<div class="entry-content">
<div><div id="wrap">lala</div></div>
<p><script type="text/javascript">window.location = "http://"</script></p>
</div>

or the best output would be (wrap and replace):

<div class="entry-content">
<div id="wrap">lala</div>
<script type="text/javascript">window.location = "http://"</script>
</div>

Thank you for your help !

Upvotes: 0

Views: 143

Answers (1)

Felix Kling
Felix Kling

Reputation: 816840

It looks like you want to remove the element but keep its content. "Unwrap" if you want to call it that.

This can be done with a little DOM manipulation:

function unwrap(element) {
    // insert all the element's children *after* the element itself
    var parent = element.parentNode;
    var children = element.childNodes;
    var before = element.nextSibling;

    // reverse iteration always inserting the previous sibling before
    // the next one
    for (var i = children.length - 1; i > -1; i--) {
        before = parent.insertBefore(children[i], before);
    }

    // remove the element
    parent.removeChild(element);
}

Then all you have to do is pass a reference to the element you want to remove to the function.

DEMO

If you really want to replace the element though, then you just have to move all child nodes to the new element and replace the old element with the new one. I call the function "rewrap" here (because "replace" doesn't indicate that the content is copied):

function rewrap(element, new_element) {
    // append all the element's children to the new element
    while (element.firstChild) {
        new_element.appendChild(element.firstChild);
    }

    // replace old element with new
    element.parentNode.replaceChild(new_element, element);
}

DEMO

Upvotes: 1

Related Questions