0

I have a 1 liner JS in the footer and I can't get getElementsByClassName to work to tweak style attributes. "Hello World" works, so it must be my syntax?

The footer code is this:

<script>
var test = document.getElementsByClassName("elementor-widget-container");
test.style.background-color = 'white';  
var widgets = document.getElementsByClassName("widgets_wrapper");
widgets.style.margin = "0px";
</script>
olcoil
  • 11
  • 1
  • `test.style.background-color` should be `test[0].style.backgroundColor` – epascarello May 27 '22 at 17:38
  • Should be a dupe of https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return [messed up my close vote] – epascarello May 27 '22 at 17:39
  • https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return this worked ty. getElementByID is easier. Too many same name classes on my site. None of the get classes functions worked. – olcoil Jun 15 '22 at 16:37

4 Answers4

0

document.getElementsByClassName returns a list of nodes. Even if there's only one.

So what you (probably) want to do is:

var test = document.getElementsByClassName[0]

In the future, try, for instance, to run console.log(test) to see what you're working with, before writing more code to manipulate that variable/element.

Yarin_007
  • 1,449
  • 1
  • 10
  • 17
0

getElementsByClassName returns an array like object, even if theres only one. You can try:

var test = document.getElementsByClassName("elementor-widget-container")[0];

or:

test[0].style.background-color = 'white';  
Jake L
  • 177
  • 1
  • 9
0

The problem is that test is an array of Node not only Node. So, you will do like this :

<script>
    let tests = document.getElementsByClassName("elementor-widget-container");
    tests.forEach( test => { test.style.background-color = 'white'; } );  
    let widgets = document.getElementsByClassName("widgets_wrapper");
    widgets.forEach( widget => { widget.style.margin = "0px"; } );
</script>
0

finally got it to work, but had to change strategy:

document.getElementById("menu-item-205").style.backgroundColor = "red";

olcoil
  • 11
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 16 '22 at 09:08