First of all, this is the code that adds a class to the HTML element has a specified selector in Javascript.
Please use this by copy-pasteing.
// get HTML element has the specified selector
var element_id = document.querySelector('#id_for_addclass');
// add class to the acquired element
element_id.classList.add("added_class");
Below are the results and a detailed explanation.
Get HTML element with specified id, and add class
This code adds a class to the element with the specified selector.
<div id="id_for_addclass">
</div>
// get HTML element has the specified selector
var element_id = document.querySelector('#id_for_addclass');
// add class to the acquired element
element_id.classList.add("added_class");
Execution result
The above code added the class named “added_class” to the specified html element.
<!-- execution result -->
<div id="id_for_addclass" class="added_class">
</div>
Reference document
This is the relevant MDN documentation that was used as reference in writing this article.
Please also see here.
Element.classList – Web API | MDN https://developer.mozilla.org/ja/docs/Web/API/Element/classList
DOMTokenList.add() – Web API | MDN https://developer.mozilla.org/ja/docs/Web/API/DOMTokenList/add
コメント