-3

Is there a way to change the text in the h2 inside a class using css or javascript? I think it is possible through JS but not sure how.

Please note that I cannot change span or give id. Also, I have multiple sections that uses the same div class "twocol-box1 superflex-content-6-12" but only one section with the H2 text "old text".

Here is what I have

<div class="twocol-box1 superflex-content-6-12">
  <h2>old text</h2>
Superman
  • 71
  • 10

3 Answers3

7

You can access the h2 inside a div whose class is "twocol-box1 superflex-content-6-12" by using javascript "querySelector" method :

const h2Tag = document.querySelector("twocol-box1 superflex-content-6-12 > h2");

Note that querySelector method acts like a CSS selector.

Then, the content of an element can be changed using the "innerHTML" property :

h2Tag.innerHTML = 'New text';
sebastiencn
  • 208
  • 2
  • 5
  • Is this how I add this? Please note that I have mutiple places on the page that uses this div class. Thanks – Superman May 19 '22 at 13:05
  • This will change the text everywhere you wrote an h2 iniside a tag with the "twocol-box1 superflex-content-6-12" class (as a direct child) as soon as the script will load – sebastiencn May 19 '22 at 13:09
3

Try

var elem = document.querySelector("div.twocol-box1.superflex-content-6-12 h2");
elem.innerHTML = "new text"

You select the "h2" Tag in a div with the classes twocol-box1 and superflex-content-6-12 and change the Text with innerHTML method

Voidy
  • 424
  • 3
  • 12
0

If There is only one div with class twocol-box1 superflex-content-6-12 who has h2 as child

document.querySelector("div.twocol-box1.superflex-content-6-12 h2").innerText = "New Value"

If Not U can use nth-child

document.querySelector("div.twocol-box1.superflex-content-6-12:nth-child(<That Div Position>) h2").innerText = "New Value"

for example if you want select the 2nd div then

document.querySelector("div.twocol-box1.superflex-content-6-12:nth-child(2) h2")
Heet Vakharia
  • 405
  • 4
  • 14
  • I have multiple div class. I tried this and it doesn't work. Am I missing something? I dunno much JS, so its possible I am missing something. Maybe a quote or something? – Superman May 19 '22 at 12:47
  • make sure in nth-child div position rank is correct, and then if it still doesn't work, can you upload code to codepen and share the link – Heet Vakharia May 19 '22 at 13:33