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

Creating new Vue components is happening towards the end of the loop

I am currently encountering an issue with my Vue components. I have structured them in a hierarchy where I have a post-index component displaying all posts, containing a post-view component for individual posts, and within that, a post-like component to ha ...

Navigating the From and To routes in Nuxt/Vue: A comprehensive guide

I am currently working on a Nuxt/Vue project. While inspecting in Dev Tools, I came across a From and To property. How can I access these properties within the Nuxt application? I have attempted to use this.$nuxt.$route, this.$nuxt.$router, and this.$rou ...

Executing a POST Request from AngularJS to a server-side script

Currently, I am in the process of developing a web application using Yeoman tools with AngularJS. However, I have encountered a challenge when trying to send a POST request to a server-side script from a controller. Below is the snippet of code from my con ...

Guidelines for creating animation for a single point in SVG Polygon

Is there a way to animate the movement of a single polygon point within an SVG using velocity.js? Your assistance is greatly appreciated! <p>Changing...</p> <svg height="250" width="500"> <polygon points="0,0 200,0 200,200 00,20 ...

I'm looking for an easy way to generate a special effect when my mouse interacts with a div using HTML, CSS, or JavaScript

I'm attempting to replicate this interesting effect where a div is surrounded by a container when the mouse hovers over it. It looks pretty cool, like in this image here: https://i.stack.imgur.com/p0epq.png Does anyone have any suggestions on how I ...

Switching to fullscreen mode and eliminating any applied styles

I'm trying to enable fullscreen mode with a button click. I've added some custom styles when the window enters fullscreen, however, the styles remain even after exiting fullscreen using the escape key. The styles only get removed if I press the e ...

Issues with Collision Detection between Canvas Rectangles and Balls

I am developing an HTML5 canvas game and encountering an issue with collision detection. The problem occurs when the ball collides with any platform - the ball's gravity should change to -1 and move upwards at the same velocity as the platforms. Howev ...

What is preventing my application (docker) from connecting to the database?

Encountering a frustrating issue here: I've developed a NodeJS application with a server listening on port number 3000. The app includes simple operations such as post, put, and read, which interact with a database running in a Docker Container on por ...

How can you prevent the browser from prompting to save your email and password when filling out a sign-up form?

I'm currently developing a PHP sign up form, but whenever I click on the sign up button, the browser prompts me to save the email and password. Is there a way to prevent this from happening? ...

Finding the main directory in JavaScript: a step-by-step guide

My website uses mod_rewrite to reformat the URLs like this: The issue arises when making AJAX calls to a file: I want to access login.php from the root without specifying the full URL or using the "../" method due to varying folder levels. So, I need a ...

The dynamic sidebar menu in Adminlte 3 with bootstrap-4 loaded from ajax is not functioning properly, presenting issues with sidebar

Is there a way to fetch dynamic sidebar menu data from the database using AJAX in the adminlte 3 dashboard along with bootstrap 4? I have tried loading the sidebar menu data dynamically using AJAX, but the sidebar open/close functionality is not working pr ...

Is it possible for the connectedCallback() method within a Custom Component to have varying interpretations based on the specific context in which it is implemented?

I have recently developed a Custom Component that incorporates a Vue instance: class ContentCardExample extends HTMLElement { connectedCallback() { const card = document.createElement('div'); card.setAttribute("id", "app") card.i ...

The app.get() method in Node JS and Express requires three parameters, and I am seeking clarification on how these parameters work

Hey there, I'm new to this and have a question regarding my code using passport-google-oauth20. app.get('/auth/google/secrets', passport.authenticate('google',{failureRedirect: '/login'}), function(req,res){ res.redirec ...

Tips for locating the index of the previously selected active class

I am currently working on a slider and have made progress up to this point. However, I am facing an issue where I cannot proceed because I need to identify the index of the item from which I removed the last active class before the click event occurs. My ...

What is the best way to send a variable or query to a Python script from PHP using an Ajax request?

A Python script I have takes parameters or a SQL query from the PHP file, which I am running by calling an Ajax function. The PHP and Ajax call code has been added here. A variable "action" is created to check different cases. While I can execute action = ...

Attempting to toggle variable to true upon click, but encountering unexpected behavior

On my webpage, I have implemented a simple tab system that is only displayed when the variable disable_function is set to false. However, I am facing an issue with setting disable_function to true at the end of the page using a trigger. When this trigger ...

When running the command "npx create-next-app@latest --ts," be aware that there are 3 high severity vulnerabilities present. One of the vulnerabilities is that "node-fetch

Just set up a fresh project with Next.js and TypeScript by following the documentation using npx create-next-app@latest --ts. Encountering multiple high severity vulnerabilities despite running npm audit fix --force, which actually adds more vulnerabiliti ...

Altering the display attribute cancels out any opacity transitions

When using JavaScript to change the opacity of an element with transition: opacity 1s, the expected duration of one second is met, as demonstrated here: onload = e => { var p = document.getElementsByTagName("p")[0]; p.style.opacity = 1; }; p { ...

Merging two individual JavaScript scripts to ensure seamless functionality for both

I am facing a challenge with utilizing two scripts simultaneously: Script 1: $(document).ready(function () { $(".tabContent").not(":first").hide(); $("ul.tabs li:first").addClass("active").show(); $("ul.tabs li").click(function () { $ ...

Is it possible to change XML using Ajax technology?

Is it possible to update a value in an XML file using JavaScript/Ajax? I've managed to access the XML file with Ajax and utilize its values in my script. Now, I want to send any updates made by the script back to the XML file on the server using Ajax ...