简体   繁体   中英

Is it possible to add a class using javascript? no id and class in the div

在此处输入图像描述

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

thanks.

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>

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');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM