skip to Main Content

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>

2

Answers


  1. You can either directly with class name nav-user-ddli (?) or this selector
    .nav-user-dd>div:nth-child(3)

    document.querySelector(".nav-user-dd>div:nth-child(3)").style.background = 'red'
    <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>
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search