“jQuery方式”用HTML和文本混合替换一个文本节点?

在我的Web浏览器用户脚本项目中,我需要替换一个文本节点,而不会影响与文本相同的父节点下的其他HTML元素。 我需要用多个节点替换它:

foo / bar; baz

需要成为:

 
foo / bar; baz

我知道jQuery没有对文本节点的大量支持。 我知道我可以使用直接DOM调用而不是jQuery。 我知道我可以做一些像$('#target').html(我的新东西+我不想改变的东西) 。 另外请注意,我想保留最初的空间,这本身似乎很棘手。

我想问一下这里的专家是, 有一种最惯用的jQuery方法吗?

您基本上想要用新内容替换第一个子节点(文本节点)。 你需要http://api.jquery.com/replaceWith/

 // Text node we want to process and remove var textNode = $("#target").contents().first(); // Break the text node up var parts = textNode.text().split(/\s/); // Put links around them var replaceWith = ""; for (var i =0; i < parts.length;i++) { replaceWith += "" + parts[i] + " "; } // Replace the text node with the HTML we created textNode.replaceWith(replaceWith); 

http://jsfiddle.net/NGYTB/1/

试试这种方法

 // nodeType = 1 corresponds to element node // You are filtering everything out other than that and // removing the textnodes from it.. // contents() will get everything including the text ​$('#target'​).contents().filter(function() { return this.nodeType != 1; }).remove(); // Then you are prepending the div with the html that needs to // replaced with the text... $('#target').prepend('mixed text and HTML'); // This makes sure you do not touch the initial img element inside the div 

如果您不想删除特定的节点类型,可以添加其他节点类型CHECK FIDDLE

试试这个..编辑版

 $('#target').html('mixed text and HTML' + $('#target').html());