Are you able to locate <td>s with identical classes using just a portion of the string?

There are multiple classes in the <td>s of my table. I am looking to identify each <td> that contains a specific string.
For instance:

<table>
    <tr>
        <td class="hello there">foo</td>
        <td class="hello here">bar</td>
        <td class="not hello">baz</td>
    </tr>
</table>

I want to locate all td elements that contain the word "hello".
Is there a way to achieve this? Simply using className == will only return exact matches. That's a given.

Answer №1

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.

Answer №2

Consider implementing a solution similar to this:

var tds = document.getElementsByTagName("td");

for (var i = 0; i < tds.length; i++) {
    var cur = tds[i];
    var the_class = cur.className;
    if (the_class.split(" ").indexOf("hello") > -1) {
        // cur has the class "hello"
    }
}

There are alternative methods available as well.

You could utilize the .classList attribute, which is not fully supported yet - https://developer.mozilla.org/en-US/docs/DOM/element.classList.

Another option is using document.getElementsByClassName - https://developer.mozilla.org/en-US/docs/DOM/document.getElementsByClassName.

You can also explore document.querySelectorAll - https://developer.mozilla.org/en-US/docs/DOM/Document.querySelectorAll.

var td_with_class = document.querySelectorAll("td.hello");

Answer №3

class="greetings friend" indicates that the td possesses two classes, greetings and friend.

Therefore, you can implement this code:

var items = document.getElementsByClassName('greetings');

Answer №4

let tableCells = document.getElementsByTagName('td'),
    filteredCells = [];
for (let i = 0; i < tableCells.length; i++){
  if (tableCells[i].className.match(/\bhello\b/i)){
    filteredCells.push(tableCells[i]);
  }
}

Utilize the RegExp match function along with the \b symbol to target table cells with the specified class. Another approach is to filter in reverse, starting with the class name and then narrowing down by tagName:

let helloCells = document.getElementsByClassName('hello'),
    filteredCells = [];
for (let i = 0; i < helloCells.length; i++){
  if (helloCells[i].tagName == 'TD'){
    filteredCells.push(helloCells[i]);
  }
}

Answer №5

An effective approach is to retrieve all elements using their tag names ("td"). Then, loop through each element and check if the word "hello" is contained within the class attribute. Feel free to ask for the code snippet if you require it!

Answer №6

Surprisingly, jQuery's hasClass wasn't even mentioned by anyone.

Alternatively, you could simply use

var allHello = $("td.hello");

Answer №7

A useful property to check for classes is .classList.

elem.classList.contains( 'world' ) 

This line of code tells us if the element has the class "world" or not.

Check out this live example: http://jsfiddle.net/X9kLs/2/

.classList is widely supported in modern browsers, but doesn't work on older versions of IE (<10).

Answer №8

Retrieve all elements with both the 'blue' and 'example' classes

document.getElementsByClassName('blue example');

And to narrow it down to a specific element:

Locate all span elements with a class of 'example'

var examples = Array.prototype.filter( document.getElementsByClassName('example'), function(elem){
    return elem.nodeName == 'SPAN';
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Traverse the initial three elements of an array using JavaScript (React)

Let's say we have a collection of 5 items: const items = [ {id: 1, name: 'book', price: 50}, {id: 2, name: 'phone', price: 450}, {id: 3, name: 'fish', price: 80}, {id: 4, name: 'apple', price: 5}, {id: 5, name: ...

Radio buttons with multiple levels

Looking to implement a unique two-level radio button feature for a specific option only. Currently, I have written a logic that will display additional radio buttons under the 'Spring' option. However, the issue is that when it's selected, t ...

Utilizing the map() function to iterate through a list of outcomes and assigning the resulting array as the state of a component in ReactJS

Currently, I am facing an issue with assigning an array value to the state in my react project. In order to do this, I have initialized my state as follows: constructor(props) { super(props); this.state = { category: [] } } My objec ...

Learn the process of dynamically loading scripts and their functions in Angular

At first, I had the following code statically placed in Index.html and it was functional. <script src="/le.min.js"></script> <script> LE.init({ token: 'token', region: 'x' }); </script> ...

How can I pass command line variables into an npm script?

I am facing an issue where I am attempting to pass a command line option (which is not stored in version control) to my main script index.js. This script performs specific actions based on a designated S3 bucket. Here is the relevant section from my packa ...

Error in Continuous Integration for Angular 4: Unable to access property 'x' of an undefined variable

i am trying to display some data on the form but encountering an error: TypeError: Cannot read property 'title' of undefined below is my component code : book:Book; getBook(){ var id = this.route.snapshot.params['id']; ...

Tips for preventing duplicate properties in Material UI when using React JS

Incorporating components from Material-UI, I have designed a form where the state of inputs is controlled by the parent component. However, I encountered an error stating "No duplicate props allowed" due to having multiple onChange parameters. Is there a w ...

Safari on iOS 11.4 ignoring the 'touch-action: manipulation' property

I ran into an issue while developing a React web app that I want to work seamlessly across different platforms. My goal was to allow users to interact with a div element by double-clicking on desktop and double-tapping on mobile devices. However, when tes ...

What is the best way to select an element that is currently visible but hidden underneath another element?

I have developed a circular graphic using primarily HTML and CSS, with some JavaScript and JQuery functionalities incorporated for text curving and planned interactions in the future. However, I've encountered an issue where clicking on the upper rig ...

Dynamically assigning column values based on object properties

I am currently utilizing the Ionic Framework along with its grid system that is reminiscent of Bootstrap. However, I believe my query leans more towards AngularJS than specific Ionic components. Here is what I have: <ion-col *ngFor="let col of row ...

What is the best way to initiate a TouchEvent in a qunit test being run by grunt using only vanilla JavaScript?

I have implemented callbacks for different touch events that require testing. For example, the 'touchstart' event utilizes touch coordinates to configure a class member: NavigationUI.prototype.touchStart = function(evt) { this.interacting = ...

What is causing Puppeteer to not wait?

It's my understanding that in the code await Promise.all(...), the sequence of events should be: First console.log is printed 9-second delay occurs Last console.log is printed How can I adjust the timing of the 3rd print statement to be displayed af ...

Steps to create a toggle feature for the FAQ accordion

I am currently working on creating an interactive FAQ accordion with specific features in mind: 1- Only one question and answer visible at a time (I have achieved this) 2- When toggling the open question, it should close automatically (having trouble with ...

Compiling TypeScript to JavaScript with Deno

Currently experimenting with Deno projects and looking for a way to transpile TypeScript into JavaScript to execute in the browser (given that TS is not supported directly). In my previous experience with NodeJS, I relied on installing the tsc compiler via ...

Troubles arising while using ng serve in Angular 2

I'm currently facing an issue during the installation process of an existing Angular application. When trying to run the application using the ng serve command, I encounter the following error message: The "@angular/compiler-cli" package was not prope ...

What is the best way to incorporate my theme classes into my React component for custom styling?

Struggling to customize my React header buttons as I can't seem to apply my classes function that utilizes useStyles(). The error seems to be coming from: className: {classes.menuButton} within my getMenuButtons function. const useStyles = makeStyles ...

Utilizing Node and Express to transform an array into a "Object" Map

For my latest project, I decided to build a web application using Node Express for the backend and Vue for the front end. While working on it, I encountered an issue where an array in an object was being converted to a map when sent to Express via jQuery. ...

An error occurred while trying to initialize the ui.bootstrap.demo module in AngularJS

Currently, I am in the process of learning angularjs and have encountered a roadblock. An error keeps popping up: ncaught Error: [$injector:modulerr] Failed to instantiate module ui.bootstrap.demo due to: Error: [$injector:nomod] Module 'ui.bootstr ...

Obtain specific information from custom fields on the product page

What am I trying to achieve? I want to create a single product page that displays custom fields which need to be filled out before the item can be added to the cart. Additionally, I have implemented a button that should take all the values entered in the ...

Transition within Vuejs moves forwards and backwards, with a unique feature that allows it to skip directly to

I am in the process of developing a slider element that consists of only 2 items. My goal is to ensure that these items smoothly slide back and forth to the left and right when I click on the back or next button. While everything functions correctly when I ...