Frage

Uhm, I've got this script but it does not work.

It's all about this line: document.getElementById('thetest').addClass('superspecial');

As soon as the class should be added (but it isn't) the whole script quits... Does anybody know why?

War es hilfreich?

Lösung

Should be:

jQuery('#thetest').addClass('superspecial');

or

document.getElementById('thetest').className += ' superspecial';

document.getElementById doesn't return a jQuery element.
That's why you get has no method error.

Andere Tipps

I know this is a bit of an old post by now, but I ran into it myself and I used a method that wasn't named before to solve it.

Instead of using

document.getElementById("name").className+='superspecial';

I used

document.getElementById("name").classList.add('superspecial');

After some research it seems that this is a fairly new way to do it that isn't supported in a lot of browser versions other than the latest. Browser requirements to use this functionality are as described here: https://www.w3schools.com/jsref/prop_element_classlist.asp

I don't know the exact difference between the two solutions, but it seems to me that getting the classList and adding to it with an existing function would be the preferable option. Especially as += is a general method of adding things to eachother that doesn't always have to work the way you expect it to.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top