Home > Back-end >  simple getElementsByClassName javascript not working in wordpress footer
simple getElementsByClassName javascript not working in wordpress footer

Time:05-28

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>

CodePudding user response:

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.

CodePudding user response:

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';  

CodePudding user response:

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>
  • Related