1

I dynamically created various images and other elements within various div elements and assigned a class to them, like:

divOM = document.getElementById('omain');
kd = document.createElement('img');
kd.src = 'pics/k0.jpg';
kd.class = 'mww';
divOM.appendChild(kd);

This works well – the debugger shows the desired result (# children with class ‘mww’). I have the (maybe naïve) hope that

wlist = document.getElementsByClassName('mww')

gives me all elements which have class=’mww’, but unfortunately it doesn’t. The debugger shows length:0 for wlist!?? Is it possible that document.getElementsByClassName doesn’t work for dynamically created elements?

hgbk
  • 23
  • 4

1 Answers1

4

Should be .className, not .class.

class is a reserved word in JavaScript.

Or use the Class List API:

kd.classList.add('mww');
Mitya
  • 33,629
  • 9
  • 60
  • 107
  • 1
    Actually, since ES5 (2009) `kd.class = 'mww';` has been perfectly valid from a code perspective. The problem is that the DOM bindings for this stuff were created before that change and in ES3 (1999, the version just before ES5) `kd.class = 'mww';` *wasn't* valid. :-| – T.J. Crowder Feb 11 '21 at 16:05
  • 1
    Interesting, didn't realise that. – Mitya Feb 11 '21 at 16:07
  • 1
    Btw, reserved words **can** be used as object properties now (that's why `promise.catch`, `generator.throw` and `import(...).default` work), but the designers of the DOM made it that way because it wasn't always so. – FZs Feb 11 '21 at 16:08
  • 1
    @T.J.Crowder Oh, I managed to write the same thing in different words (I didn't see your comment while I was typing) – FZs Feb 11 '21 at 16:09
  • 1
    @FZs - But yours has great examples! :-) – T.J. Crowder Feb 11 '21 at 17:10
  • Excellent! Thanks a lot. It works with .className! – hgbk Feb 12 '21 at 11:59