Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

javascript - Replacing / Manipulating element in html string using jquery

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...