简体   繁体   中英

How can i get correct className from multiple classes in Vanilla Javascript

I have a parent element with a single child element. I would like to get return only the parent element's classname based on its classname. That means now in the console log, i getting 3 classes. But only want 'one' here. Because the 'parent' variable is targetted the class '.one'. Hopes someone can help me on this. If you did'nt understand ask me, so that i'll come up with more details. Thanks in advance.

 let parent = document.querySelector(".one"); let correctClass = parent.className; console.log(correctClass);
 <div class="one two three"> <div class="child-element">Child Element</div> </div>

No need to access the element at all when you already know the selector:

 const selector = ".one"; const parent = document.querySelector(selector); const correctClass = selector.slice(1); console.log(correctClass, parent);
 <div class="one two three"> <div class="child-element">Child Element</div> </div>

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