Hedge
Hedge

Reputation: 16766

Insert HTML after certain paragraph of HTML string

I've got a HTML-string I'd like to render but append some HTML after the 2nd paragraph first.

function insertStuff() {
  //var string = "<div><p>paragraph 1</p><p>paragraph 2</p><p>paragraph 3</p></div>"; works
  var string = '<p><img src="http://example.com/my-cool-picture.png" alt="alt text"></p><p>2nd paragraph</p><p>3rd paragrpah</p>' // doesn't work
  var parsedHtml = $(string)
  parsedHtml.find("p:nth-child(2)").after("<p>My cool insert</p>")
  return parsedHtml.html()
}

This works for the HTML string above but the following one only return the <img> after invoking parsedHtml.html()

What am I doing wrong?

Upvotes: 1

Views: 403

Answers (4)

sunil chugh
sunil chugh

Reputation: 9

when you use find() with a selector it will search inside that selector (in child nodes) that why when you use string with div tag you are getting the desired result and when you delete div the problem occured

Upvotes: 0

Ram
Ram

Reputation: 144739

That's because html method as getter returns html content of the first element in the set. You should either wrap all the top-level elements in the set with another element and read it's html content or iterate through the set and concatenate each element's outerHTML property.

parsedHtml.map(function() { return this.outerHTML; }).get().join('');

If you want to get the innerHTML of all the elements in the set, replace outerHTML with innerHTML.

Upvotes: 2

Satpal
Satpal

Reputation: 133453

Since you are use .html() it will return html of first element.

You can wrap your content in a div like

var parsedHtml = $('<div />').html(string)

Then your code will work.

function insertStuff() {
  var string = '<p><img src="http://example.com/my-cool-picture.png" alt="alt text"></p><p>2nd paragraph</p><p>3rd paragrpah</p>'
  var parsedHtml = $('<div />').html(string)
  parsedHtml.find("p:nth-child(2)").after("<p>My cool insert</p>")
  return parsedHtml.html()
}

alert(insertStuff())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 4

Manoj
Manoj

Reputation: 5071

Try this

function insertStuff() {
  var string = '<div><p><img src="http://example.com/my-cool-picture.png" alt="alt text"></p><p>2nd paragraph</p><p>3rd paragrpah</p></div>';
  var parsedHtml = $(string)
  parsedHtml.find("p:nth-child(2)").after("<p>My cool insert</p>")
  return parsedHtml.html()
}

You should put this string in a div as parent.

Upvotes: 2

Related Questions