Reputation: 23
Say, I have something like this:
<div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br/> Duis aliquet imperdiet nunc. Duis vel ipsum sed dui imperdiet auctor.
</div>
I want to add an image before the <br></br>
tags. How to do it using JQuery?
JQuery's append, prepend, after and before seems to be of no use. Please help
Upvotes: 0
Views: 120
Reputation: 208
<div class="lorem">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br /> Duis aliquet imperdiet nunc. Duis vel ipsum sed dui imperdiet auctor.
</div>
$('.lorem br').before(imghtml);
Or you can use
$('.lorem br').insertBefore(imghtml);
Make sure you replace the jquery selector above with something specific, most of the time there are a lot of break tags in pages, and you don't want the image you're trying to place to be inserted everywhere in your page. I would suggest you target the paragraph you want to do that to by using a class or an ID tag.
Updated after reading your comments:
Add a class attribute to the targeted
tag so that you can specifically target it in your jQuery selector. Something like this:
<div class="lorem">
Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br class="targetedbr" /> Duis aliquet imperdiet nunc. Duis vel ipsum sed dui imperdiet auctor.
</div>
$('.lorem br.targetedbr').insertBefore(imghtml);
Upvotes: 1
Reputation: 1394
You don't need to close <br>
tags, and they should also be formatted <br />
See this fiddle for how to do it.
$('br').before('<span style="background-color:red; color:white">Image Here!</span>')
In response to your question, you can add .first()
to select the first element.
http://jsfiddle.net/9j70mxsz/1/
In response again, the :nth-child(n)
selector.
http://jsfiddle.net/9j70mxsz/2/
Upvotes: 0