jQuery allows us to add new or existing elements anywhere in the DOM. All we need to do is identify the target element and use a jQuery inbuilt method to place elements before or are after the target element. Check out some DOM insertion methods here
Let us see an example where a paragraph is to be inserted before the last paragraph. We will be using the before method which will insert new content before each element, in the set of matched elements.
Consider the following HTML
If we have to insert a new paragraph before the last paragraph, use the following code:
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.5.1.min.js"> </script> <script type="text/javascript"> $(function () { $("#btnOne").click(function () { $('#divOne > p:last-child') .before('<p>Dynamic Para</p>') }); }); </script>
As you can see, we first use a selector which selects the last para in divOne and then use before method to insert a paragraph before the matched element
OUTPUT
Tweet
No comments:
Post a Comment