Skip to content
Advertisement

search and replace text inside html of div in javascript but not text inside tag

I’ve some HTML structure and i want to search particular text inside that HTML structure. see below example

<h1>Try to span some text on this page</h1>
    <div>
        span is a <span>paragraph</span>.</div>
    <p class="span ddd">This 123is a paragraph.1</p>

<div class="span ddd">This is some span in a div element.</div>

Now if I’m searching for “span” text then, “span” word should be wrapped with div tag. But only “span” word in text and not from class or other tags.

i want output like this (wrap using div or span)

<h1>Try to <span class="search">span</span> some text on this page</h1> <div> <span class="search">span</span> is a <span>paragraph</span>.</div> <p class="span ddd">This 123is a paragraph.1</p> <div class="span ddd">This is some <span class="search">span</span> in a div element.</div>

Advertisement

Answer

<div id="wrapper"> 
    <h1>Try to span some text on this page</h1>
  <div>
    span is a <span>paragraph</span>.
  </div>
    <p class="span ddd">This 123is a paragraph.1</p>

    <div class="span ddd">This is some span in a div element.</div>
</div>

I have modifed your html by enclosing with a wrapper for getting my selector. But you can use your own selectors.

$(document).ready(function(){
   var str=$('#wrapper').html();
   $('#wrapper').html(str.replace( new RegExp(" span ","g"),"<div>span</div>"));
});

This code will do what you need. Here is the jsffiddle for this.

If your problem is fixed then please don’t forget to mark this as solved. Thanks.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement