Home > Back-end >  How can I locate the 3rd div using DOM Traversing?
How can I locate the 3rd div using DOM Traversing?

Time:08-31

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" >
  <div ></div>
  <div >John Doe</div>

  <div >
      <div id="btnLogoutF" >test</div>
      <div id="btnLogoutF" >
      <a href="#">test</a>
      </div>
  </div>
</div>

CodePudding user response:

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" >
  <div ></div>
  <div >John Doe</div>

  <div >
      <div id="btnLogoutF" >test</div>
      <div id="btnLogoutF" >
      <a href="#">test</a>
      </div>
  </div>
</div>

CodePudding user response:

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" >
          <div ></div>
          <div >John Doe</div>

          <div >
              <div id="btnLogoutF" >test</div>
              <div id="btnLogoutF" >
              <a href="#">test</a>
              </div>
          </div>
        </div>

  • Related