1

I have a string that contains HTML, for example

var myString = "<div><p>testing</p></div>";

I need to target p and replace "testing" with something else, say "Hello World". I would normally use

$("p").innerHTML = "Hello World";

However, this is part of a string, not part of the DOM. How can I use jQuery's selector system to select from a string of HTML?

Keavon
  • 6,837
  • 9
  • 51
  • 79
  • This does not look like it's a duplicate of that. He even stated he's not using jQuery. – Keavon Jul 21 '14 at 22:15
  • Question 1: Do you have a DOM or are you doing something fancy out of a DOM? Question 2: Are you adverse to "hacky" solutions like having a place holder in the DOM and using that? – Jon P Jul 22 '14 at 00:45
  • @JonP In my case I have a template that I pull as text into a variable with AJAX and I want to add content to a part of that template before putting it in the template's holder in the real DOM. I'd normally target it with jQuery, but it's still in a variable. I can add it to the DOM and then place content in it, but it will be more tricky to target the exact one and there might be a few milliseconds where there is no content. – Keavon Jul 22 '14 at 01:22
  • The correct way to do this using jquery is `var s = '
  • text
  • '; $.parseHTML(s).find("p").text("Hello World")`. Not sure why this question is marked a duplicate of one that does not ask for the jquery method of doing this – smac89 Jan 06 '17 at 04:31