My table’s <td>s contains multiple classes. I would need to find every <td> that contains the given string.
For example:
<table>
<tr>
<td class="hello there">foo</td>
<td class="hello here">bar</td>
<td class="not hello">baz</td>
</tr>
</table>
I would need to find every td containing “hello”.
Can it be done? The simple className == will only return exact matches. Of course.
That’s what
getElementsByClassNameis for:This’ll select any elements that have the class
hello.Note: The
classattribute contains a space separated list of class names.If you need to support IE8 and below, use this:
Here’s a demo: http://jsfiddle.net/AJEsp/
As per @mplungjan’s suggestion, here’s a short explanation of the bitwise tilde (~) trick:
The
indexOffunction returns an integer with the position of the found substring, so that'abc'.indexOf('b')will return1,'abc'.indexOf('c')will return2, and so forth. If the substring is not found, it will return-1.The
~character is one of the bitwise operators whcih inverts all the bits. Sidestepping the complicated issue of how exactly this happens, all we need to know now is that~-1returns0, while using the tilde on anything else would return a truthy value.So,
~'str'.indexOf('substring')can be treated as a Boolean of whether the substring was found.