How to Change this JS to Use GetElementsByClassName
Ad
I am attempting to make this JS add a class to another class (not an id):
var d = document.getElementById("div1");
d.className = d.className + " other class";
ie.
var d = document.getElementsByClassName("div1");
d.className = d.className + " other class";
I have a pen here that you can toy with: http://codepen.io/xkurohatox/pen/wMWKKM
Ideally it would be nice for something that functions with IE 8+ and modern browsers. JAVASCRIPT ONLY PLEASE (No JQuery please).
Any suggestions? Thanks!
Ad
Answer
Ad
document.getElements.className
actually returns a collection instead of a single value.
You need to access individual elements by using array-bracket notation
.
var d = document.getElementsByClassName("gold")[0]'
The above gets the first element with the required class name.
Here's a demonstration
var gold = document.getElementsByClassName("gold");
for (var i = 0; i < gold.length; i++) {
gold[i].classList.add("bold");
}
.gold { background: gold; }
.bold { font-weight: bold; }
<p class="gold">Paragraph 1</p>
<p>Paragraph 2</p>
<p class="gold">Paragraph 3</p>
Ad
source: stackoverflow.com
Related Questions
Ad
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad