How do I add a class to a given element?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试): 问题: I have an element that already has a class: Now I want to create a Javascript function that will add a class to the div (not replace, but add). How can I do that? 回答1: Add a space plus the name of your new class to the className property of the element. First, put an id on the element so you can easily get a reference. Then var d = document.getElementById("div1"); d.className += " otherclass"; See also element.className on MDN . 回答2: The easiest way to do this without any framework is to use element.classList.add method. var element =