Aircrafter
Aircrafter

Reputation: 89

Wrap text following a particular element with <p>

I've got some HTML like this:

<div class="text">
    <img src="http://placehold.it/50x50"/><a href="http://www.example.com" class="ht">the link</a>
    this element doesn't look right, the text displays next to the link
</div>
<div class="text">
    <img src="http://placehold.it/50x50"/><a href="http://www.example.com" class="ht">the link</a> 
    <p>this is a proper kind of element, i want them wrapped in paragraphs or at least looking like they've been wrapped in paragraphs</p>
</div>

and I was wondering if it would be possible to make the text from the first example <div> display below the link, like wrapping a <p></p> around the text, with jQuery. It's not possible to change the HTML because it's a user-generated comments kind of project, and I can't exactly force the user to put <p></p> around their text. Most of them do, but some of them don't so I need to find a solution to make them all display the same.

I've done some research and I found this answer: Selecting text only following certain elements using javascript/jquery but it doesn't really answer my question as that's based on a particular fixed structure of text and what I have as text can really be anything the user inputs and I need it to display below the image and the link, which display on the same line. This solution: Wrap text after particular symbol with jQuery also doesn't work for me because there is no set HTML that I can use to identify the unwrapped text. This one: Find text in element that is NOT wrapped in html tags and wrap it with <p> also doesn't do what I need because sometimes we have people using <b></b> and <i></i>

Other things I've tried:

So if anyone could help me out with this I'd be really grateful, thank you!

EDIT: Here's an example of what I want:

Upvotes: 0

Views: 144

Answers (1)

madalinivascu
madalinivascu

Reputation: 32354

try something like:

$('.text').each(function() {
  var el = $(this).clone().find('img,.ht');//get the image and the title 
  var text = el.remove().end().html();//remove the elements, get the remaining html
  $(this).html(el).append('<p>' + text + '</p>');//add the p with the remaining html

});
p {color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text">
  <img src="http://placehold.it/50x50" /><a href="http://www.example.com" class="ht">the link</a>
  this element doesn't look right, the text displays next to the link
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="text">
  <img src="http://placehold.it/50x50" /><a href="http://www.example.com" class="ht">the link</a>
  this element doesn't look right, the <b>text displays next</b> to the <i>link</i>
</div>

Upvotes: 1

Related Questions