-2

I have an string, let's say it is like below:

<div class="myClass">
   Some Text.
</div> 
<div class="otherClass">
   Some Text.
</div>

Now, I have to parse the div with myClass class name and replace some text (say, replace Text. with Content.)

How can I achieve this with regex? I can replace content of all the divs, but I need to replace the content of that particular div.

Any help will be highly appreciated.

warrior3hsan
  • 175
  • 1
  • 1
  • 11
  • 5
    [For reference](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454) – Will Richardson Oct 04 '15 at 08:23

1 Answers1

4

Don't use regular expressions.

// Parse the HTML using the DOM (a temporary element
// in this case, which won't be added to the body)
var tempElement = document.createElement("div");
tempElement.innerHTML = 
    '<div class="myClass">\
       Some Text.\
    </div> \
    <div class="otherClass">\
       Some Text.\
    </div>';

// Store elements with the same class in an array
// since classes are meant to be re-usable
var elements = [];
for (var i = 0, l = tempElement.children.length; i < l; i++){
  var el = tempElement.children[i];
  if (el.className === 'myClass')
    elements.push(el);
}

// Run a replace on the contents of each element
// in the array
for (var i = 0, l = elements.length; i < l; i++){
  var el = elements[i];
  el.innerHTML = el.innerHTML.replace('Text', 'Content');
}

// Output result
document.write(tempElement.innerHTML);
SeinopSys
  • 8,787
  • 10
  • 62
  • 110