Amechi
Amechi

Reputation: 800

Adding a Div tag to wrap around LI elements

I would like to dynamically add a pair of Div tags and a class to wrap a set of elements in the DOM. How would I go about doing this?

Html

<div class="right-bottom"> <!-- this is the div tag I would like to add to wrap the content below-->
    <li class="">
        <a href="">Diffusion Tensor Imaging</a>
        <article class="article-body" data-asynchtml-target="">
            <div class="loader"></div>
        </article>
     </li>

</div> 

JavaScript

<script type="text/javascript">
    var div = document.createElement('div');
</script>

Upvotes: 2

Views: 4960

Answers (2)

christian314159
christian314159

Reputation: 639

Here is an example: get parent, detach element, append wrap to parent, append element to wrap.

function wrapElement(element) {
    var parent = element.parentNode,
        wrap   = document.createElement('div');

    wrap.classList.add('wrap');
    element.remove();
    parent.appendChild(wrap);
    wrap.appendChild(element);
}

http://jsbin.com/hagovune/1/edit?html,css,js,output

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82241

You can use .wrap() with appropriate selector to target li elements. something like this:

$('.article-body').closest('li').wrap('<div class="right-bottom"></div>')

See Documentation.

Upvotes: 2

Related Questions