-1

I have a structure something like this:

<div class="tower">
    <div class="E0">abc</div>
    <div class="GU">123</di
</div>

No my problem ist that I want to get the inner classNames 'E0' & 'GU' in javascript, and I only know the outer className 'tower'.

So while 'tower' stays the same, 'EO' and 'GU' may be other names and i want to have the classNames (as a String).

Thanks for your help (and sorry for this probably stupid question)

  • Does this answer your question? [JavaScript getting an elements class without any libraries](https://stackoverflow.com/questions/3453799/javascript-getting-an-elements-class-without-any-libraries) – Anurag Srivastava Mar 27 '20 at 15:25

3 Answers3

2

You can use children property of the parent node, then use array .map() method to loop over each of them to get className like:

const children = document.querySelector('.tower').children;
const classes = [...children].map(el => el.className)
console.log(  classes )
<div class="tower">
    <div class="E0">abc</div>
    <div class="GU">123</di
</div>
palaѕн
  • 64,836
  • 15
  • 100
  • 121
0

Something like this?

let clss = [...document.querySelector(".tower").querySelectorAll("div")]
    .map(div => [...div.classList.values()].map(val => val))
console.log(clss)
<div class="tower">
    <div class="E0 B0">abc</div>
    <div class="GU">123</div>
</div>
mplungjan
  • 134,906
  • 25
  • 152
  • 209
-1
var first = document.querySelector(".tower div:first-child").className;

var last = document.querySelector(".tower div:last-child").className;
  • 2
    Please don't post only code as an answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually of higher quality, and are more likely to attract upvotes. – Mark Rotteveel Mar 28 '20 at 08:20