skip to Main Content

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>

4

Answers


  1. Chosen as BEST ANSWER

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

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


  2. 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.

    Login or Signup to reply.
  3. 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';  
    
    Login or Signup to reply.
  4. 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>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search