1

enter image description here

See the attached image, I would like to add a class where the arrow is pointing.

thanks.

0

2 Answers 2

2

You can get all the div elements with

getElementsByTagName('div')

Then you can add it to the second element by adding the new class to the element at indice 1

document.getElementsByTagName('div')[1].classList.add('foo');

document.getElementsByTagName('div')[1].classList.add('foo');
.foo {
  background-color: purple;
}
<div>
  <div>HI
    <div>
    </div>
  </div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

0

The getElementsByTagName() method returns a collection of all elements in the document with the specified tag name (don't forget to check the length so you won't get a null exception)

const divs = document.getElementsByTagName('div');
if (divs.length > 1){
    divs[1].classList.add('your-class');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.