扩展或扩展元素范围内容?

时间:2017-09-26 22:26:02

标签: javascript jquery

是否可以扩展元素的内容?假设我们有文本“hello world of javascript”但目前只有“hello”包含在标签中。我们如何扩展范围,以便hello和world现在都在span标记内,而单独留下“javascript”?

如:

<p><span class="bold">hello</span> world of javascript </p>

变为:

<p><span class="bold">hello world</span> of javascript </p>

1 个答案:

答案 0 :(得分:0)

// Get the plain text that's into the <p> tag (i.e hello world) and put it 
// as the inner text of span
$('span').html($('p').text());

// Clear the plain text nodes of <p> tag
$("p").contents().filter(function(){ 
  return this.nodeType == 3; 
})[0].nodeValue = "";