4

Supposed that we have this html:

<div class="some-class">This is the content</div>
<h2 class="some-class">This is to be replaced</div>

In jquery, we can replace the content of the h2 using:

$('h2.some-class').html('string to replace');

This will replace the h2.some-class without changing content of div.some-class. Now, the current page doesn't have the luxury of using a framework or jquery for this instance - only javascript.

How can we replace that tag with specific class using plain javascript without affecting other tags with the same class?

barudo
  • 665
  • 4
  • 13

2 Answers2

6

You can use document.querySelector, like so:

document.querySelector('h2.some-class').innerHTML = 'string to replace';

for Multiple Elements:

document.querySelectorAll('h2.some-class').forEach(function(el) {
      el.innerHTML = "string to replace";
    });
shreyas d
  • 774
  • 1
  • 4
  • 16
0

You can use querySelector method of HTML elements combined with innerText property of elements:

    document.querySelector('h2.some-class').innerText = document.querySelector('div.some-class').innerText;
    //or any other text

Note that querySelector method will only return first match. If you have more h2 tags with some class class, you can use document.querySelectorAll method and iterate over retrieved collection.

If you want to insert only text (without any html tags) to element, it is not necessary to use innerHTML property (even due to safety reason it is not advisable), innerText will do just fine.

Furman
  • 2,017
  • 3
  • 25
  • 43