Accessing Elements by Class in JavaScript
JavaScript does not natively provide a getElementByClass() function. To access elements based on their class, you can use the following techniques:
1. Using getElementsByClassName():
This method returns a collection of elements with the specified class name. However, it is only supported in modern browsers and does not allow for nested or multiple classes.
Example:
const elements = document.getElementsByClassName("className");
2. Using getElementsByTagName('*') with Looping:
This approach iterates through all the elements on a page and checks their class list for a match. It works in all browsers, including older ones.
Example:
function replaceContentInContainer(matchClass, content) { const elems = document.getElementsByTagName('*'); for (let i = 0; i < elems.length; i++) { if ((' ' + elems[i].className + ' ').indexOf(' ' + matchClass + ' ') > -1) { elems[i].innerHTML = content; } } }
This revised code allows you to replace the contents of elements based on their class name, even if multiple elements on the page share the same class.
The above is the detailed content of How Can I Access Elements by Class in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!