One way to target specific elements is by using the getElementsByClassName
method:
document.getElementsByClassName('hello');
This code snippet will find all elements with the class name hello
.
Note: The class
attribute can contain multiple class names separated by spaces.
If you need compatibility with IE8 and older versions, you can achieve similar functionality like this:
var elements = document.getElementsByTagName("td"),
helloElements = [],
i = elements.length;
for (i--) {
if ( ~(' ' + elements[i].className + ' ').indexOf(' hello ') ) {
helloElements.push(elements[i]);
}
}
Check out a working demo here: http://jsfiddle.net/AJEsp/
In response to @mplungjan's suggestion, here's a brief explanation of the bitwise tilde (~) trick:
The indexOf
function returns the position of a substring within a string. For instance, 'abc'.indexOf('b')
would return 1
, and 'abc'.indexOf('c')
would return 2
. If the substring is not found, it returns -1
.
The ~
character is one of the bitwise operators that inverts all bits. When applied to anything except -1
, it results in a truthy value. Therefore, ~-1
becomes 0
, indicating that the substring was found.
Hence, ~'str'.indexOf('substring')
can be interpreted as a Boolean representing whether the substring was located in the string or not.