Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I locate the 3rd div using DOM Traversing?

Can anyone help me with how I can locate the 3rd div inside my parent nav-user-dd
using Traversing the dom? My goal is to locate the nav-user-ddli and add a class it using Dom Traversing. Thanks

.nav-user-ddli {
  background: yellow
}

.nav-user-ddli.addClass {
  background: green
}
<div id="btnNavUser" class="nav-user-dd">
  <div class="nav-user-img"></div>
  <div class="nav-user-name">John Doe</div>

  <div class="nav-user-ddli">
      <div id="btnLogoutF" class="nav-user-ddli-item">test</div>
      <div id="btnLogoutF" class="nav-user-ddli-item">
      <a href="#">test</a>
      </div>
  </div>
</div>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can do it by selecting the parent element with getElementById

const btnNavUser = document.getElementById("btnNavUser")

then, traverse its children with children property

const thirdChild = btnNavUser.children[2] 

finally, add the desired class with

thirdChild.classList.add("addClass")
const btnNavUser = document.getElementById("btnNavUser")
const thirdChild = btnNavUser.children[2]
thirdChild.classList.add("addClass")
.nav-user-ddli {
          background: yellow
        }

        .nav-user-ddli.addClass {
          background: green
        }
<div id="btnNavUser" class="nav-user-dd">
          <div class="nav-user-img"></div>
          <div class="nav-user-name">John Doe</div>

          <div class="nav-user-ddli">
              <div id="btnLogoutF" class="nav-user-ddli-item">test</div>
              <div id="btnLogoutF" class="nav-user-ddli-item">
              <a href="#">test</a>
              </div>
          </div>
        </div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading