How to wrap a sentence with a certain word in Jquery

213 Views Asked by At

How do I do this one in jquery? Say I have

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

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

if the container has this phrase "The requested quantity for" then wrap the entire sentence in

<h1></h1>

this will be the output:

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

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

THANKS :)

3

There are 3 best solutions below

6
On BEST ANSWER

you can try this:-

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

or you can also use wrapInner:-

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

Answer for updated question:-

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

Demo for wrapInner

Demo

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