如何用 Jquery 中的某个单词包裹句子

How to wrap a sentence with a certain word in Jquery

如何在 jquery 中执行此操作?说我有

<div class = "container">
      The requested quantity for "ITEM" is not available

      <span>Other word</span>
</div>

如果容器有这个短语"The requested quantity for" 然后将整个句子包裹在

<h1></h1>

这将是输出:

<div class = "container">
      <h1>The requested quantity for "ITEM" is not available</h1>

      <span>Other word</span>
</div>

谢谢 :)

你可以试试这个:-

$('.container').html('<h2>'+$('.container').text()+'</h2>');

或者你也可以使用wrapInner:-

$('.container').wrapInner('<h2/>');

更新问题的答案:-

$('.container').contents()
    .filter(function(){return this.nodeType === 3})
    .wrap('<h2 />');

Demo for wrapInner

Demo

$("#container").html('<h1>'+$("#container").html()+'</h1>');
$('div.container').each(function(index){
    if($(this).html().indexOf("The requested quantity for") > -1)
    {
        $(this).html("<h1>" + $(this).html() + "</h1>");
    }
});