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?

4
  • This does not look like it's a duplicate of that. He even stated he's not using jQuery. Commented Jul 21, 2014 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? Commented Jul 22, 2014 at 0: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. Commented Jul 22, 2014 at 1:22
  • The correct way to do this using jquery is var s = '<li>text</li>'; $.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 Commented Jan 6, 2017 at 4:31

2 Answers 2

1

You can turn any HTML into a parse-able jQuery object(s).

jQuery - selectors on a html string

$('p', myString).text()
Sign up to request clarification or add additional context in comments.

1 Comment

That allows me to retrieve the string but not edit it (as meni181818 mentioned in his answer). +1 as it is useful.
-1

note that you cant use:

$("p", myString).text( "Hello World" );

because is not 'Editable' DOM (isContentEditable: false)

1 Comment

It looks like you were downvoted by someone else because that is more of a comment than an answer. I suggest deleting the answer and posting it as a comment.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.