28

I have a html string (not DOM), that I want to manipulate using jquery. Why doesn't this work:

var html = '<div><h4><a class="preview-target" href="content.html">Headline</a></h4></div>';
console.log(html);

var elem = $('h4', $(html));
// replace "Headline" with "whatever" => Doesn't work
elem.replaceWith("whatever");

console.log(html);

I have a jsfiddle here for testing.

The above code is just a simplified example. The real html is much more complex, that is, I definitely need to rely on jQuery for manipulating the html string.

0

3 Answers 3

57

When you modify the jQuery object, it will not change the value in the string literal.

You can use

var html = '<div><h4><a class="preview-target" href="content.html">Headline</a></h4></div>';
console.log(html);

var $html = $('<div />',{html:html});
// replace "Headline" with "whatever" => Doesn't work
$html.find('a').html("whatever");

console.log($html.html());

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

4 Comments

"When you modify the jQuery object, it will not change the value in the string literal." Why is that? Seems like a bug to me?!
@ArunPJohny I don't understand var $html = $('<div />',{html:html}); What exactly does this bit of code do? Looks like you create an object? What is the <div /> about? Does that add to the original HTML or is it selecting the div within the existing string?
@AdamYoungers $('<div />',{html:html}); - creates a dom div element, and set the value of html as its innerHTML....
It will not change the value in the string literal - important key is here. "$($('select').html())" will do the trick and do whatever you want like $($('select').html()).find('h4').remove()
6

You can find the h4 then call the replaceWith method.

var html = $('<div><h4><a class="preview-target" href="content.html">Headline</a></h4></div>');

console.log(html.html());
html.find('h4').replaceWith('whatever')
console.log(html.html());

Jsfiddle

Comments

2
var html = '<div><h4><a class="preview-target" href="content.html">Headline</a></h4></div>';
var replaced=html.replace("Headline","whatever");
console.log(replaced);

Try this

2 Comments

ok, but why isn't my above code not working? My code above is just a simplified example, the real code is much more difficult html that I cannot manipulate using simple replace method. So I need jQuery
@A.Wolff ok, but that would only work for my minimal working example code, not for my much more complex code. There I need to rely on jQuery. I updated the question with regards to this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.