Change class of div by accessing with access to its parent only

Viewed 32

I am trying to change the class of an dynamic element that I cannot directly access in code. I can access its parent so I've been targeting it like so: .menu > div. That div has a class of "col-xs-12 col-sm-4 col-md-3 col-lg-2". I want to be able to change the class of .menu > div to class "new-menu"

I don't quite get how I can do that. Would I use getElementsByClassName somehow? How can I access that specific div? It has to be targeted because there are other elements with "col-xs-12 col-sm-4 col-md-3 col-lg-2" but with different parent classes.

This code is from a dynamic menu that uses the same code to generate submenus so it's a bit confusing to target the submenu that I want.

1 Answers

You can play with querySelector and classList here.

var selectDiv = document.querySelector(".main > div.col-xs-12.col-sm-4.col-md-3.col-lg-2");

selectDiv.classList.remove("col-xs-12", "col-sm-4", "col-md-3", "col-lg-2");

selectDiv.classList.add("new-menu");
.main div,.main2 div {
  padding:20px;
  background: #f90;
  font-weight: bold;
  margin-bottom: 10px;
  font-size: 18px;
}

.main .new-menu {
  background: #000;
  color: #fff;
}

.main2 div {
  background: #fd0
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Document</title>
  </head>
  <body>
    <div class="wrapper">
      <div class="main">
        <div class="col-xs-12 col-sm-4 col-md-3 col-lg-2">
          This is the div which needs to update the classname.
        </div>
        <div class="col-xs-12 col-sm-4">
          This is the other div in same parent.
        </div>
      </div>
      <div class="main2">
        <div class="col-xs-12 col-sm-4 col-md-3 col-lg-2">
          This is the div in different parent.
        </div>
      </div>
    </div>
  </body>
</html>

Related