Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace content of tag with class in javascript

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?

like image 484
barudo Avatar asked Sep 15 '25 01:09

barudo


1 Answers

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";
    });