Define CSS styles based on the content of a specific cell within a table

Is there a way to target a <td> in CSS based on its content value?

    <table>
      <tr>
        <td>Name</td>
        <td>John</td>
      <tr>
    </table>

For instance, how can I apply the color:black style to the td element containing the value "John"? Can this be achieved using only CSS? If so, how?

Answer №1

Instead of focusing on setting classes, the question revolves around reacting to the content within certain elements.

According to the current CSS Spec, this is generally not achievable. However, there are some exceptions:

  1. The :empty pseudo-selector, which determines if an element is completely empty or not.

    td:empty {
      background-color: lightgreen;
    }
    

For a more detailed example, check out: http://codepen.io/MattDiMu/pen/pbJbOx

  1. One workaround is to place the content in a data-attribute and style based on it.

HTML

    <td data-val="Name"></td>

CSS

    td::after {
      content: attr(data-val);
    }
    [data-val="John"] {
      background-color: lightgreen;
    }

For a detailed example of this method, visit: http://codepen.io/MattDiMu/pen/OXVXaO

While this approach can be considered a "hack," it should be used cautiously because:

  • Most screen readers may not recognize the value as they disregard CSS content.
  • You may lose the ability to use a different content in the ::after pseudo-element.
  • This method is limited to displaying text and cannot showcase HTML structures.

It's worth noting that the ":contains" pseudo class was ultimately removed and did not become a part of the Recommended CSS Spec. As far as I know, it is not supported in any major browsers.

Answer №2

One way to tackle this problem with JavaScript is by iterating through all td elements and checking their content. If the content matches a certain criteria, a class can be added to the element. In the example provided, a class is appended to td elements that have inner content of "John".

var elements = document.getElementsByTagName("td");
for (var i = 0; i < elements.length; i++) {
  if(elements[i].innerHTML == "John") {
    elements[i].className += " " + "highlight";
  }
}
.highlight {
  color: red;
}
<table>
  <tr>
    <td>Name</td>
    <td>John</td>
  <tr>
</table>

It's important to note that the example above serves as a basic demonstration. You can customize and expand upon this solution to suit your specific requirements.

Answer №3

Learning about HTML and CSS

<table>
  <tr>
    <td>Name</td>
    <td class="red-flag">John</td>
  <tr>
</table>

<style>
 .red-flag{
   color:red;
 }
</style>

Utilizing jQuery for a different approach:

 $("td:contains('John')").css('color', 'red');

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

Is it possible to switch states in Angular UI Router without altering the URL?

The feature of multiple nested views in the ui-router is quite convenient as it allows for seamless transitions between different states within an application. Sometimes, there may be a need to modify the URL while navigating through states, while at othe ...

Spontaneous Link with JQuery and Colorbox

Just to clarify, I have no programming experience so please explain everything in simple terms. I am currently using a .js script within SharePoint and it's working perfectly! <!DOCTYPE html> <html> <head> <meta charset= ...

Tips for updating the background color of a dropdown menu in the navigation bar

I am attempting to increase the size of the dropdown menu and change its background color. Currently, I can only modify the color of the links and the surrounding area. .navbar a { width: 125px; text-align: center; ...

What is the best way to determine the length of an array using input from an HTML form?

Currently, I am in the process of developing a PHP file and one feature that I would like to implement is creating an array as illustrated in Example 1. As far as my understanding goes, an Array functions like a list where items can be added as shown in Ex ...

When trying to click the button in Navbar.jsx, I encounter an error when attempting to invoke the setShowCart(true) function

I've encountered an issue while trying to call the setShowCart(true) function in Navbar.jsx. I'm unsure of how to fix this. import React from 'react' import Link from 'next/link'; import {AiOutlineShopping} from 'react-ic ...

jQuery UI Tab displays the initial tab

I have an ASP:Button control in tab-2. When I insert something in the database in the onClick method, it returns to the first tab but I want it to stay on the current tab. Also, the page must reload. How can I achieve this? <asp:Button ID="btnAddCont ...

Execute jQuery after Angular has completed its loading process

I'm currently working on making some small adjustments to an existing website. This website was originally created using Angular. While my code is written with jQuery, I do have the flexibility to use any type of JavaScript necessary. Despite this, ...

Parsing error: 'Unexpected token' found in JSON while attempting to access an external file

Currently working on implementing backbone for a new project along with underscore, requirejs, jquery, and bootstrap. Things are progressing smoothly as I aim to include static survey question data into one of the data models. { "defaultOptions": { ...

How can I prevent CSS styles from affecting all the tables on my website?

One issue I'm facing is that the CSS code intended for one table is affecting all the other tables on my website. Here is an example of the CSS code: tr:last-child td:last-child { border-bottom-right-radius:3px; } /*effects map*/ td { background: ...

The index "visible" in $_POST has been flagged as not defined

I am currently developing a PHP project and have a form that needs to be submitted. The form code is as follows: <h2>Create Subject</h2> <form action="create_subject.php" method="post"> <p>Subject name: <inp ...

What is the best way to create a toggle function for a specific span element that switches between showing more or

I came up with this solution: $(".morelink").click(function(){ $(this).siblings(".DescMore").show(); $(this).hide(); }); After tweaking the code, only the content related to the clicked link will be shown. Here's what I did: Here is the mod ...

Retrieving HTML file from server directory within extjs HTML editor

Can anyone help me figure out how to successfully load an HTML file into the code editor? I have attempted using the code below, but it doesn't seem to be working: loader : {url : 'uploads/temp.html', autoload : true} ...

The Dynamic Kendo Grid construction encountered an invalid template issue

In my project, I'm working on creating a dynamic Kendo UI grid with columns that are dynamically generated. However, I'm encountering an issue where the data is not rendering properly onto the grid. The backend of this project involves using ASP ...

Effective HTML element placement with CSS styling

My HTML code includes a form containing a table. Take a look: This is the Code I'm Using: <html> <head></head> <body> <form onsubmit="" id="form1" action="" method="post" name="form1" style="position: rela ...

Having issues with contenteditable functionality not functioning properly on elements that are dynamically generated

Creating an unordered list dynamically and adding items to it on a button click. Appending it to a section with contenteditable set to true, but encountering issues. The code snippet below demonstrates the process: // Create text input var categoryInput = ...

Do all links need an href attribute?

I'm inquiring about this because I have specific links that function as buttons to retrieve content through ajax, eliminating the need for href tags. (This inquiry is driven by SEO considerations) ...

Tips for correctly cloning a table row:

Currently, I am engaged with a Django project that involves incorporating a form within a table structure. <table name="mytable" id="table_purchase" role="grid"> <thead> <tr> <th class="text-center" hidden>No</th& ...

Is the × symbol added from JavaScript not able to be clicked on?

In my javascript code, I have added HTML content dynamically using the following method: var response = { message: "sample messsage" }; $('#main-content').append( '<div class="alert alert-danger alert-dismissable">'+ & ...

The edge of the 'parent' element is obscured by the :after element

I am trying to create a transparent outlined button with a shadow in the shape of the button. However, I am facing an issue where the border of the button appears behind the :after element. You can see the problem below. Adding overflow: hidden to the tog ...

Updating ng-table within an Angular controller

Having encountered an unusual issue with ng-table. Here is a snippet of code from my controller: this.category = "Open"; this.category = ["Open", "Accepted", "Rejected"]; this.dataItems = []; var _this = this; this.$scope.$watch("vm.category", function( ...