문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top