0

I googled my fingers wound and all the solutions I found won't work.
Im trying to replace a div like the following:

var modal = document.getElementById("first");

// Get modal content and replace the footer with content
var oldContent = modal.innerHTML;

// Set modal content
modal.innerHTML = oldContent.replace(/<div class="two">(.*?)<\/div>/, '<div class="two">' + 'Content' + '</div>');
<div class="outer" id="first">
  <div class="one">This is the first one</div>
  <div class="two">Second one</div>
</div>

Im trying to replace everything in the second div.
Currently my code is like this and I tried so select everything with regex, but it just wont work.

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
nn3112337
  • 459
  • 6
  • 21
  • 2
    Why are you using a reg exp? Makes no sense to do that. – epascarello Oct 01 '15 at 12:26
  • Why not `document.getElementByClassName("two").innerHTML = "Content"` – Abhi Oct 01 '15 at 12:27
  • Do not use regular expression for parsing html/xml. This is why libraries like jQuery exist! – avidenic Oct 01 '15 at 12:27
  • Don't use RegEx for this, but the reason your code doesn't work is because you just weren't running the HTML against the JS (at least on your post). When I created a single post, it worked. – Ruan Mendes Oct 01 '15 at 12:33

2 Answers2

1

You could be using querySelector for what you need:

document.querySelector('div.two').innerHTML = 'Content';
Buzinas
  • 11,597
  • 2
  • 36
  • 58
0

Makes no sense to change content with a regular expression when you can access the element. Explained here on why it is bad idea.

Just reference the element from the modal and set the innerHTML or textContent with the value you want.

modal.getElementsByClassName("two")[0].innerHTML = "new text";

or

modal.querySelector(".two").innerHTML = "new text";
Community
  • 1
  • 1
epascarello
  • 204,599
  • 20
  • 195
  • 236