First of all: you have not closed the quotation mark at class="box . Must be class="box"
Secondly: you need to write getElement S ByClassName , because the collection of elements is selected according to the class.
Thirdly: since this is a collection, an array, it means that you need to access the collection element and only set the property:
<div class="box"> text </div> <input type="button" value="Текст" onclick="document.getElementsByClassName('box')[0].style.background ='red'"/>
For coloring all elements of the class .box you need to organize a cycle, emnip
Like that:
<div class="box"> text </div> <div class="box"> text22 </div> <div class="box"> text333 </div> <input type="button" value="Текст" onclick="var x = document.querySelectorAll('.box'); for (var i = 0; i < x.length; i++) { x[i].style.backgroundColor = 'green'; }"/>
In general, it is better to remove the script from the markup, because it is awful to watch
document.querySelector("#test").addEventListener("click", modifyBG, false); function modifyBG() { var x = document.querySelectorAll(".box"); for (var i = 0; i < x.length; i++) { x[i].style.backgroundColor = "red"; } }
<div class="box"> text </div> <div class="box"> text222 </div> <div class="box"> text33 </div> <input type="button" value="Текст" id="test"/>
And it is worth making styles in css , and in the script only assign the necessary classes, identifiers, etc.
document.querySelector("#test").addEventListener("click", modifyFunc, false); function modifyFunc() { var x = document.querySelectorAll(".box"); for (var i = 0; i < x.length; i++) { x[i].classList.add('my-style'); } }
.my-style { background: #ff0000; border: 3px solid green; padding: 10px; margin: 10px; }
<div class="box"> text </div> <div class="box"> text222 </div> <div class="box"> text33 </div> <input type="button" value="Текст" id="test"/>