如何使用jQuery解包文本?

czu*_*zuk 18 html jquery

如何使用jquery从HTML标签中解包文本?

例如,如何转换此HTML

<p>A <i>sentence</i> with <b>bold words</b>.</p>
Run Code Online (Sandbox Code Playgroud)

into(即删除粗体标签)

<p>A <i>sentence</i> with bold words.</p>
Run Code Online (Sandbox Code Playgroud)

仅使用jQuery而不使用正则表达式?

Nic*_*ver 39

你可以这样做:

  $("b").each(function() {
    $(this).replaceWith(this.childNodes);
  });
Run Code Online (Sandbox Code Playgroud)

注意:这会保留您可能在其中.text()转换它的任何HTML .

如果你想完全剥离,<b></b>你可以在jQuery 1.4+中更轻松地使用Cheeso的答案:

$("p").html(function(i,h){ return h.replace(/<b>/g,'').replace(/<\/b>/g,''); }); 
Run Code Online (Sandbox Code Playgroud)


小智 7

我先变得非常喜欢wrapInner,然后解开.

例如,如果您尝试打开超链接

<a id="anId" href="#">sample text</a>
Run Code Online (Sandbox Code Playgroud)

然后你可以通过打开超链接

$('#anId').wrapInner('<span/>');
$('#anId span').unwrap();
Run Code Online (Sandbox Code Playgroud)