-2

I would like to implement a small javascript code in The Twenty sixteen theme in WordPress itself.

This is the HTML Code I want to change on the Page:

<p class="site-description">Example Text</p>

I want to change a classname:

document.getElementsByClassName("site-description").className ="Site-example-class";    

But The class site-description is not changing after using FireBug on the page.

Also when I want to select the text of the headline with this:

document.getElementsByClassName("site-description").innerHTML ="Hello There";    

it is not working.

Martin
  • 57
  • 1
  • 9
  • `getElementsByClassName`, as the name implies, returns a collection of elements. If you only need the first one, you need to insert `[0]`: `document.getElementsByClassName("site-description")[0].innerHTML ="Hello There";` I recommend using `document.querySelector(".site-description")` instead, which here requires the class dot like in CSS but only returns the first match. –  Nov 22 '17 at 15:25
  • 1
    Possible duplicate of [What do querySelectorAll, getElementsByClassName and other getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method) –  Nov 22 '17 at 15:26
  • Where is this code running? Is it in a document ready? In the `head`? In the footer? – random_user_name Nov 22 '17 at 15:56
  • Thanks got it done. – Martin Nov 24 '17 at 07:58

2 Answers2

0

getElementsByClassName() returns an array of matching elements. You could reference the first result like this. document.getElementsByClassName("site-description")[0]

Matthew Nie
  • 629
  • 5
  • 10
0

document.getElementsByClassName("site-description") will return an array of all the elements with this class name. So if you want to modify the innerHTML of those, you need to do so inside the array. If you only have one element with this class name, this is the way to do it :

document.getElementsByClassName("site-description")[0].innerHTML = "Your new HTML here"
Arnaud Stephan
  • 406
  • 3
  • 16