使用jquery替换/操作html字符串中的元素

时间:2014-03-03 09:34:11

标签: javascript jquery string

我有一个html字符串(不是DOM),我想用jquery操作。为什么这不起作用:

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);

我有一个jsfiddle here用于测试。

上面的代码只是一个简化的例子。真正的html要复杂得多,也就是说,我绝对需要依赖jQuery来操作html字符串。

3 个答案:

答案 0 :(得分:42)

修改jQuery对象时,它不会更改字符串文字中的值。

您可以使用

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());

演示:Fiddle

答案 1 :(得分:6)

你可以找到h4,然后调用replaceWith方法。

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

答案 2 :(得分: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);

试试这个