We can use the jQuery
before() methods to add content after or before a html element.
In this example, we have an image with two buttons below it.
If we click the Insert Before button, we can see that text is added before the image.
If we click Insert After, text is added after the image.
We will take a look at our html page to see how this works.
$("img").before("<b>Text Added Before Element.</b>");
$("img").after("<i>Text Added After Element.</i>");
<img src="http://www.youaccel.com/admin/uploadscript/tmp/o5ymiVGp.jpg" width="150" height="150"><br><br>
<button id="btn1">Insert before</button>
<button id="btn2">Insert after</button>
<body> tags, we have two buttons, each with a unique id btn1 and btn2.
We also have our image tag which contains the source of our image.
Now taking a look at our script, we can see there is a
click event attached to btn1. When clicked, we use the
before() method, to attach some text before the image.
btn2 also has a
click event. When clicked, text is attached after the image.