Home >Web Front-end >CSS Tutorial >How to Style Elements with getElementsByClassName on Event Occurrence?
Changing Element Style with getElementsByClassName on Event
Elenments with a given class can be styled on event occurrence using the getElementsByClassName method. However, since this method returns an array of elements, it's essential to iterate through the array to apply the style to all matching elements. Additionally, inline event handling attributes like onmouseover are deprecated.
Error in Code
The code provided has several errors:
Solution
Example
<code class="javascript">window.onload = function() { var aElements = document.getElementsByClassName('classA'); var bElements = document.getElementsByClassName('classB'); document.getElementById('elementA').addEventListener('mouseover', function() { changeColor(aElements, 'red'); }); document.getElementById('elementB').addEventListener('mouseover', function() { changeColor(bElements, 'blue'); }); function changeColor(elements, color) { for (var i = 0; i < elements.length; i++) { elements[i].classList.add('class-color-' + color); } } };</code>
The above is the detailed content of How to Style Elements with getElementsByClassName on Event Occurrence?. For more information, please follow other related articles on the PHP Chinese website!