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

Click the "Add to Cart" button to make a purchase

Recently, I've been working on modeling an add to cart feature using jQuery. However, I have encountered a small issue that I'm trying to troubleshoot. When I click the mybtn button, the model displays and functions correctly, but there seems to ...

JavaScript is incorrectly showing the array as empty despite containing strings

I am experiencing an issue with my array of strings in JavaScript. Despite having strings in the array when I print it in the console, the forEach function runs 0 times and JS claims the array is empty when I print its size. What could be causing this?http ...

Fade out when the anchor is clicked and fade in the href link

Is it possible to create fade transitions between two HTML documents? I have multiple HTML pages, but for the sake of example, let's use index.html and jobs.html. index.html, jobs.html Both pages have a menu with anchor buttons. What I am aiming to ...

What is the process for retrieving the value of `submit.preloader_id = "div#some-id";` within the `beforesend` function of an ajax call?

In my JavaScript code, I have the following written: var formSubmit = { preloaderId: "", send:function (formId) { var url = $(formId).attr("action"); $.ajax({ type: "POST", url: url, data: $(formId).serialize(), dataTy ...

Python Selenium test on AngularJS UI slider implemented

I've been experimenting with setting up a UI slider (Label=ON/OFF, Slider, Apply button) using Angular JS in combination with selenium. Here's an example of the code I've been working on: jsfiddle In my attempts, I tried using the followin ...

What is the best way to retrieve the URL from a specific HTML tag?

I am attempting to extract all URLs that have id='revSAR' from the provided HTML tag using a Python regex: <a id='revSAR' href='http://www.amazon.com/Altec-Lansing-inMotion-Mobile-Speaker/product-reviews/B000EDKP8U/ref=cm_cr_dp ...

Evaluate the advancement of a test using a promise notification for $httpBackend

I am currently utilizing a file upload feature from https://github.com/danialfarid/angular-file-upload in my project. This library includes a progress method that is triggered when the xhr request receives the progress event. Here is an excerpt from the so ...

Angular's scope allows for the application of CSS classes exclusively to the first div element

Every 2 seconds, a JavaScript function is being called that updates a specific div on the view when a certain condition is met. <div id="ball_{{ballIndex}}">{{ball}}</div> This is controlled by the ng controller. var myCounter = 0; ...

Dynamically add a CSS class to the <head> tag in real

Within this function, my goal has been to dynamically append gradClass in order to apply a gradient background to a div. function applyGradient(upto) { var gradStyle = "background: -webkit-linear-gradient(left, #ff1a00 20%,#ffffff 30%);" ...

Exploring the Differences between HTML Values in HTML and jQuery

Can someone assist me with comparing HTML values to check for equality? I am looking to compare the values of two select elements in HTML and needing guidance on how to accomplish this. Specifically, I want to determine if the selected values from both s ...

Searching patterns in Javascript code using regular expressions

I am dealing with two strings that contain image URLs: http://dfdkdlkdkldkldkldl.jpg (it is image src which starts with http and ends with an image) http://fflffllkfl Now I want to replace the "http://" with some text only on those URLs that are images. ...

JavaScript horizontal slider designed for a seamless user experience

Currently, I am in the process of developing a slideshow that includes thumbnails. While my slideshow is functional, I am facing an issue with limited space to display all thumbnails horizontally. I am considering implementing a horizontal slider for the t ...

What could be causing the issue of React not showing the messages of "hello" or "goodbye"?

I have a page with a single button that is supposed to display either "hello world" or "goodbye world" when clicked. However, I am facing issues as the messages are not showing up as expected. Below is a screenshot of what the menu items look like when ca ...

What is the best way to organize class usage within other classes to prevent circular dependencies?

The engine class presented below utilizes two renderer classes that extend a base renderer class: import {RendererOne} from "./renderer-one"; import {RendererTwo} from "./renderer-two"; export class Engine { coordinates: number; randomProperty: ...

The number input component that is meant to be reusable is experiencing functionality issues within the NUXT framework

I have a reusable input component that is being used in various places. Everything works well with the number input, but the issue arises when I completely clear the input. This action triggers a warning message in the console: [Vue warn]: Invalid prop: t ...

Ways to remove unnecessary div containers in Nuxt js?

This is an example of my page: https://i.sstatic.net/CYCRL.png Showing the Nuxt layout: <template> <div> <Nuxt /> </div> </template> After being compiled by Nuxt, it generates: https://i.sstatic.net/CYdX3.png You ...

Leveraging jQuery for Adding Text to a Span While Hovering and Animating it to Slide from Left to

<p class="site-description">Eating cookies is <span class="description-addition"></span>a delight</p> <script> var phrases = new Array('a sweet experience', 'so delicious', 'the best treat', ...

Exploring the functionalities of AngularJS' ng-options when working with select elements

In my search through other posts, I came across this issue but couldn't find a solution. Here is the array in question: $scope.items = [ {ID: '000001', Title: 'Chicago'}, {ID: '000002', Title: 'New York' ...

Is there a way to modify the standard width of semantic-ui sidebars?

I'm trying to adjust the width of semantic-ui sidebars, which are originally 275px wide. Where should I include the css/js code to make them wider or narrower? Here is their default code: .ui.sidebar { width: 275px!important; margin-left: -275 ...

Encountering difficulties in sending a JavaScript array through jQuery ajax request

I'm feeling hesitant to ask this, but I can't figure out why my code isn't working. Here's what I have: <script> var formArray = new Array(); formArray['start'] = "one"; formArray['stopat'] = "two"; formArray ...