jQuery Dom Wrap Manipulation

.wrap()
//Original HTML
<p>test<p>

//after jQuery.wrap()
$("p").wrap("<div></div>") 

//Yields HTML
<div><p>test</p></div>

.unwrap()
//Original HTML
<div><p>test</p></div>

//jQuery.unwrap()
$("p").unwrap() 

//Yields HTML
<p>test</p>

.wrapAll()
//Original HTML
<p>test1</p>
<p>test2</p>

//jQuery.wrapAll()
$("p").wrapAll("<div></div>") 

//Yields HTML
<div>
   <p>test1</p>
   <p>test2</p>
</div>

.wrapInner()
//Original HTML
<p>test1</p>

//jQuery.wrapInner()
$("p").wrapInner("<strong></strong>") 

//Yields HTML
<p><strong>test1</strong></p>
Example$.wrap(), $.unwrap(), $.wrapInner(), $.wrapAll()
Source Code Expand
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<!-- Javascript -->
<script type="text/javascript">
$(document).ready(function (){
    $("#ele433").click(function(){
        if($(this).text() == "wrap"){
            $(this).text("unwrap");
            $("#ele432").wrap("<div class=\"ex2\"></div>");            
        }else{
           $(this).text("wrap");
           $("#ele432").unwrap();            
        }    
    });

    $("#ele434").click(function(){
        if($(this).text() == "wrap all"){
            $(this).text("unwrap all");
            $("#ele431 li").wrapAll("<div class=\"ex2\"></div>");
        }else{
            $(this).text("wrap all");
            $("#ele431 li").unwrap();
        }
    });

    $("#ele435").click(function(){
        if($(this).text() == "wrap inner"){
            $(this).text("unwrap inner");
            $("#ele431 li").wrapAll("<font color=\"red\"></font>");
        }else{
            $(this).text("wrap inner");
            $("#ele431 li").unwrap();
        }
    });
});
</script>

<!-- HTML -->
<a name="#wrap-unwrap-wrapinner-wrapall"></a>
<style>
#example-section43 .ex1{
    float:left;margin-right:10px;
    margin-bottom:10px;
    border:1px solid black;
    width:100px;height:60px;
    text-align:center;    
}

#example-section43 .ex2{    
    border:5px solid red;        
    width:100px;height:60px;
}
</style>
<div id="example-section43">    
    <div id="ele432" class="ex1">div1</div>
    <div style="clear:both"></div>
    <button id="ele433" type="button">wrap</button>
    <br><br>
    <div id="ele431">        
        <ul>
            <li>item 1</li>
            <li>item 2</li>
            <li>item 3</li>
        </ul>
    </div>    
    <div style="clear:both"></div>
    <button id="ele434" type="button">wrap all</button>&nbsp;
    <button id="ele435" type="button">wrap inner</button>&nbsp;
</div>




comments powered by Disqus