jQuery Dom Outter Manipulation

.after()
//Original HTML 
<div>anchor</div> 

//after jQuery.after()
$("div").after("<span>test</span>");

//Yields HTML 
<div>anchor</div><span>test</span>

.before()
//Original HTML
<div>anchor</div>

//after jQuery.before()
$("div").before("<span>test</span>");

//Yields HTML
<span>test</span><div>anchor</div>

.insertAfter()
//Original HTML
<div>anchor</div>

//after jQuery.insertAfter() 

$("<span>test</span>").insertAfter("div");

//Yields HTML
<div>anchor</div><span>test</span>

.insertBefore()
//Original HTML
<div>anchor</div>

//after jQuery.insertBefore()
$("<span>test</span>").insertBefore("div");

//Yields HTML
<span>test</span><div>anchor</div>
Example$.after(), $.before(), $insertAfter(), $.insertBefore()
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 (){
    $("#example-section42 button").click(function(){
        var text = $(this).text();

        if(text == "after"){
            $("#ele421").after("<span> after</span>");
        }else if(text == "before"){
            $("#ele421").before("<span>before </span>");
        }else if(text == "insertAfter"){
            $("<span> insertAfter</span>").insertAfter("#ele421");
        }else if(text == "insertBefore"){
            $("<span>insertBefore </span>").insertBefore("#ele421");
        }else if(text == "Reset"){
            $("#ele420").html("<span id=\"ele421\" style=\"color:red\">" + 
                              "This is a test string </span>");            
        }
    
    });
});
</script>

<!-- HTML -->
<a name="#after-before-insertafter-insertbefore"></a>
<div id="example-section42">    
    <div id="ele420">
        <span id="ele421" style="color:red">This is a test string</span>
    </div>
    
    <button id="ele422" type="button">after</button>&nbsp;
    <button id="ele423" type="button">before</button>&nbsp;
    <button id="ele424" type="button">insertAfter</button>&nbsp;
    <button id="ele425" type="button">insertBefore</button>&nbsp;&nbsp;    
    <button id="ele425" type="button">Reset</button>&nbsp;    
</div>



comments powered by Disqus