How to change style of div in js

how do i change the display of div x from none to inline-block using js .

<div class="box" id="one" onclick="play()">
                <div class="x">
                    <div id="arm1"></div>
                    <div id="arm2"></div>
                </div>
                <div class="o"></div>
            </div>

this is the js code i was using

var player = "o";

function play() {
    if (player === "o") {
        var m = document.getElementById('one').getElementsByClassName('x');
        m.style.display = "inline-block"
        console.log(m);
    }
}

but i am getting this error .

image

getElementsByClassName, as the name suggests, return an array-like structure with all the element that matches,

so

m.style.display

won’t work, since m is a list of elements, not the single element.

You can access each element like in any regular JS array: m[0] and work on that, or use querySelector instead of elementsByClassName to select a single node.

Hope it helps :+1:

2 Likes

Exactly as @Marmiz says.

getElementsByClassName returns an HTMLCollection, so in order to access first found element in this collection you need to use [0] index, in your code this would look like:

var player = "o";

      function play() {
        if (player === "o") {
          var m = document.getElementById("one").getElementsByClassName("x")[0];
          m.style.display = "inline-block";
          console.log(m);
        }
      }

However, in my opinion if you are only interested in the first element with class x use Document.querySelector method:

function play() {
        if (player === "o") {
          var m = (document.querySelector(".x").style.display = "inline-block");
          console.log(m);
        }
      }

Let me know if you have more questions

1 Like