Getting the text value from a table in JavaScript is a straightforward process. By using

I am working with a table displaying available hotel rooms and want to change the text color to green if the room is marked as "available." Is there a way to check the innerHTML of a td element to see if it contains the word "available"?

var status = document.querySelectorAll("td");
status.forEach(td => {
  if (td.innerHTML === "available") {
    td.classList.add("available-green");
  }
});
.available-green {
  color: green;
}
<table>
  <tr>
    <td>booked</td>
    <td>available</td>
    <td>available</td>
    <td>booked</td>
  </tr>
</table>

Answer №1

There are a few issues that need to be addressed:

  1. document.querySelectorAll will return a NodeList, which is a collection of elements when querying for the <td> tag. In order to handle multiple elements, it is recommended to loop through each element in the NodeList using .forEach.

  2. Currently, there is no reference to the .classList, so calling

    classList.add("available-green");
    will not produce any results. When utilizing a forEach loop, the current element (the first parameter of the .forEach method) can be used to change the classList accordingly.

  3. The variable status is predefined within the window object. It is advisable to avoid using such global variables to prevent unexpected behavior.

  4. Although not mandatory, it is generally recommended to use .textContent instead of .innerHTML when retrieving text content from an element, especially if HTML is not being manipulated.

Refer to the example below for a practical demonstration:

var tableData = document.querySelectorAll("td");

tableData.forEach(function(element) {
  if(element.textContent === "available") {
    element.classList.add("available-green");
  }
});
.available-green {
  color: lightgreen;
}
<table border=1>
  <tr>
    <td>booked</td>
    <td>available</td>
    <td>available</td>
    <td>booked</td>
  </tr>
</table>

Answer №2

The concept of textContent in the Node interface refers to the text content found within a node as well as its descendants.

let checkStatus = document.querySelectorAll("td");
checkStatus.forEach(function(element) {
  if (element.textContent === "available") {
    element.classList.add("available-green");
  }
});
.available-green {
  color: green;
}
<table>
  <tr>
    <td>booked</td>
    <td>available</td>
    <td>available</td>
    <td>booked</td>
  </tr>
</table>

Answer №3

For more information, be sure to check out the MDN documentation

let statuses = document.querySelectorAll("td");
statuses.forEach(status => {
  if (status.innerHTML === "available") {
   status.classList.add("available-green");
  }
})
.available-green {
  color: green;
}
<table>
  <tr>
    <td>booked</td>
    <td>available</td>
    <td>available</td>
    <td>booked</td>
  </tr>
</table>

Answer №4

When using querySelectorAll, it returns a node list that can be manipulated like an array. We use a status array to check the values and loop through it.

var Status = document.querySelectorAll("td");
    console.log(Status);
    Status.forEach(element=>{
      if (element.innerHTML === "available"){
      element.classList.add("available-green");

      }
    })
.available-green {
      color: green;
    }
<table>
  <tr>
    <td>booked</td>
    <td>available</td>
    <td>available</td>
    <td>booked</td>
  </tr>
</table>

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

Button to access overlay menu on my map with OpenLayers 3

I am trying to add a menu button on top of my map that, when clicked, will display a window. I have created the map div and the overlayMenu button div, but unfortunately, the button is not showing up where I want it to. I would like the button to be locate ...

What is the best method for sending a document to a web API using Ajax, without relying on HTML user controls or forms?

I have successfully utilized the FormData api to upload documents asynchronously to a web api whenever there is a UI present for file uploading. However, I now face a situation where I need to upload a document based on a file path without relying on user ...

Guide to Implementing i18n-iso-countries Library in React

I am currently developing a React application and attempting to utilize the i18n-iso-countries package to retrieve a countries object in English where keys represent iso codes and values represent country names. This process is straightforward in Node.js, ...

Show text upon hovering using jQuery

I am currently exploring jquery and trying to implement a functionality where text is displayed upon hovering over a div element. My basic html page consists of squares, with one of them rotating when a button is clicked. I now want to show some text withi ...

Next-Auth: Access Session in _app.js Directly Without Using getServerSideProps

When working with React.js and React-Auth, it's important to note that calling server-side functions such as getServerSideProps can prevent you from exporting your project using next export. Below is the content of my pages/_app.js, which I structured ...

Having trouble with adding a class on scroll?

My challenge is to extract the header from this website, by adding an additional class when the user scrolls at a position greater than 0. I thought it would be easy, but Java always presents problems for me. Here’s the code I came up with: <!DOCTY ...

The inability of Chrome and Firefox browsers to open Windows folders directly from a hyperlink is a common

My link is directing to a Windows folder using its directory path. Surprisingly, it works perfectly fine in Internet Explorer but fails to work in Chrome and Firefox. How can I resolve this issue? The structure of my link looks like this: <a href="&bs ...

tips for transferring API JSON response parameters to material ui table

I'm currently working on creating a table with the material UI. My goal is to populate the rows of the table based on the data received from an API response. The challenge I'm facing is that the API response includes an array of objects with mult ...

Creating animated reactions in discord.js is a goal of mine, however, I am encountering an issue that needs to

Last year, I asked this question and received helpful answers. However, there is still a problem that I couldn't figure out. Since I am unable to comment on the previous answers, I have decided to add a new question client.on('message', mess ...

What is the best approach to accumulate model data in an Angular JS service or controller through a series of consecutive calls?

I am facing a challenge where I need to display the results of multiple REST server calls on a single page using AngularJS. The initial call retrieves details about a specific product, including the IDs of other related products. My goal is to not only s ...

Utilizing an Angular foreach loop for restructuring JSON data

I currently have an ng-repeat function that outputs arrays of objects in the following format: [ {"day":"10","title":"day","summary":"summary","description":"ok","_id":"53f25185bffedb83d8348b22"}, {"day":"3","title":"day","summary":"summary","description" ...

Enable next-i18next to handle internationalization, export all pages with next export, and ensure that 404 error pages are displayed on non-generated pages

After carefully following the guidelines provided by i18next/next-i18next for setting up i18n and then referring to the steps outlined in this blog post on locize on how to export static sites using next export, I have managed to successfully generate loca ...

Setting up React Router in a nested directory with a flexible route structure

As a newcomer to react router, I am seeking guidance on setting it up in a specific scenario. Imagine we have a PHP application running on 'http://www.example.com'. Within this setup, there is a react application located at 'http://www.examp ...

Varying levels of scaling on iPhone and iPad

I am currently working on a website project for my friend's brother and everything is running smoothly (for the most part). The layout of the site is designed with a centered container, leaving approximately 15-20% space from the left side. However, ...

Order of tabs, dialog, and forms customization using Jquery UI

I'm currently working on a jquery dialog that contains a form split into multiple tabs. In order to enhance keyboard navigation, I am looking for a way to make the tab key move from the last element of one tab to the first element of the next tab. Cur ...

How can you update an image's source when hovering over it?

My goal is to switch the image source upon mouseover using a combination of asp.net and javascript. Here is the code I am currently using: <asp:ImageButton id="button" runat="server" Height="65px" ImageUrl="~/images/logo.png" OnMouseOver="src='~ ...

Updating the CSS style of an inner DIV using JavaScript

Can you provide guidance on how to modify the background color using JavaScript for the different styles listed below? i) Internal Style sheet and/or ii) External Style sheet I am currently working with the card deck slide show available at https://githu ...

Can Next.js 13 support the usage of axios?

Despite trying to implement the SSG operation with the fetch option {cache: 'force-cache'}, I consistently received the same data even when the mock server's data changed. I found that using the fetch option {cache: 'no-store'} do ...

Guide to aligning a component in the middle of the screen - Angular

As I delve into my project using Angular, I find myself unsure about the best approach to rendering a component within the main component. Check out the repository: https://github.com/jrsbaum/crud-angular See the demo here: Login credentials: Email: [e ...

Ways to conceal rows within an implicit grid

In the code snippet below, CSS Grid is used to adjust the number of columns for wider containers. When dealing with narrower containers (such as uncommenting width: 80vw or resizing the example), implicit rows are added (with only two being specified in th ...