Home  >  Article  >  Web Front-end  >  How to Style Elements with getElementsByClassName on Event Occurrence?

How to Style Elements with getElementsByClassName on Event Occurrence?

Barbara Streisand
Barbara StreisandOriginal
2024-10-24 07:39:30945browse

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:

  1. The getElementsByClassName method argument is missing. It should specify the class name to be fetched.
  2. The ID attribute in "
  3. Multiple elements with the same ID are present on the page ("colorswitcher B"), making the getElementById call ambiguous.
  4. The getElementsByClassName call is not cached, which can be inefficient if multiple events occur.

Solution

  1. Use document.getElementsByClassName('className') to fetch the collection of matching elements.
  2. Use addEventListener to attach event handlers.
  3. Cache the result of getElementsByClassName for performance.
  4. Use external CSS classes instead of inline style attributes to maintain code readability and maintainability.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn