1

I have HTML like this in a string:

<div style="" class="">
    <div style="" class="">
        <h1>test</h1>
        <p>
            text
        </p>
    </div>
</div>

How can I use jQuery to remove the <div>'s and just keep the inner HTML:

<h1>test</h1>
<p>
    text
</p>
1
  • What do you mean by "keep"? Is there another element you want them appended to? Commented Mar 4, 2015 at 12:27

2 Answers 2

4

use .unwrap();

from the docs:

Description: Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place.

$('p, h1').unwrap().unwrap();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="" class="">
    <div style="" class="">
        <h1>test</h1>
        <p>
            text
        </p>
    </div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

1

The simplest is to use unwrap method like this:

$('div').contents().unwrap('div');

Check the demo below.

$('button').click(function() {
    $('div').contents().unwrap('div');
});
div {
    border: 1px red solid;
    padding: 10px;
}
div div {
    border-color: green
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="" class="">
    <div style="" class="">
        <h1>test</h1>
        <p>
            text <button>Remove div's</div>
        </p>
    </div>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.