Concealing a <TD> element in jQuery if it contains a regular space character

Discover how to style your HTML and jQuery

<table class="wrap_class_adv">
    <tr>
        <td>321</td>
        <td>123</td>
        <td> </td>    <--- Located here
    </tr>
</table>

The jQuery Code

$('.wrap_class_adv tr').each(function () {
    if ($(this).find('td').text() === " ") {
        $(this).class('visibility', 'hidden');
    }
});

Check out this code snippet on JSFiddle!

What's the best way to hide a TD element with visibility: hidden when it contains only a space?

Answer №1

Make sure to include the jQuery link before attempting to set a class, as opposed to trying to modify the css directly.

Check out this example on my fiddle:

<table class="wrap_class_adv">
    <tr>
        <td>321</td>
        <td>123</td>
        <td> </td>
    </tr>
</table>

<script>
$('.wrap_class_adv td').each(function () {
    if ($(this).text() === " ") {
        $(this).addClass('hidden');
    }
});
</script>

<style>
    td {border:1px solid #000;}
    .hidden {visibility: hidden;}
</style>

http://jsfiddle.net/yeqgtb06/26/

By the way, don't overlook linking jQuery in your code.

Answer №2

You're definitely heading in the right direction. It looks like you're trying to target td elements within each tr that contain a space.

One approach you could take is to use the filter method on the td elements, selecting only those that have a space present. You can then adjust the styling of those selected td elements using CSS properties as needed.

Important Note: Whether there's one space, multiple spaces, or no content at all within the td element, it won't be affected by this filter. However, if the content includes &nbsp;, it will continue to remain visible based on your requirements mentioned in the question title.

$('.wrap_class_adv tr').each(function () { // Loop through each tr
    $(this).find("td").filter(function() { // Filter td elements
        return (this.innerText == "");     // Check for empty innerText
    }).css('visibility', 'hidden');        // Toggle visibility with css
});
td { border: 1px solid #000; padding: 4px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="wrap_class_adv">
    <tr>
        <td>321</td>
        <td>123</td>
        <td> </td>    <!-- Contains one space -->
        <td>   </td>  <!-- Contains three spaces -->
        <td>&nbsp;</td>  <!-- &nbsp; remains visible -->
    </tr>
</table>

Answer №3

To conceal any element that includes a space, regardless of other content, utilize the contains selector in this manner

$("td:contains(' ')")

If you aim to hide elements solely with a space character, you may need to select all of them and then iterate through the results while examining their contents:

$('td').each(function() {
    if ($(this).html() == ' ')
        $(this).css('visibility', 'hidden');
});

Answer №4

Consider applying a class to td elements:

View this code snippet to see how it specifically hides td elements instead of tr elements.

CSS:

td {
border:1px solid #000;
}
.hidden {
    display: none;
}

JS:

$(document).ready(function () {
$('.wrap_class_adv tr').each(function () {
    $(this).find('td').each(function () {
        if($(this).text().trim() === "")
        $(this).addClass('hidden');
    });
});
});

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

Determine the product of the total value entered in a textbox and the percentage entered in another textbox to

I've been searching high and low to crack this puzzle, attempting to create a simple calculation on change event using 3 textbox inputs Textbox for Item Cost Manually entered Discount Percentage value e.g. 29 Total: which will be the result ...

When using jQuery CSS3, the second instance of ''rotate()'' within the ''transform: rotate() translate() rotate()'' will override the first one

I've been working on a code snippet that positions div elements around a circle: angle = 0; mangle = 0; for(i = 1; i<= count; i++) { $("#p" +i).css("transform", "rotate(" + angle + "deg) translate(250px) rotate("+mangle+"deg)"); an ...

Inquiry about an IP board forum

When using an IP board forum, you may have noticed that you can easily click on the "quote" button for any message you wish to quote. Then, when you navigate to the "add reply" page, the quoted messages are automatically included in your response form. I ...

Can you explain the meaning of the code snippet i = (i + 1 == count) ? 0 : i + 1;?

I recently utilized this particular line of code in my jQuery plugin, but I find myself struggling to fully grasp its functionality. Below is a snippet of the plugin's code: Could someone provide me with an explanation? (function ($) { $.simpleS ...

Unable to retrieve response from Node Express using Ajax when uploading files with Multer

Currently, I am utilizing multer for image uploads and it is functioning flawlessly. While I can view the data being printed to the console, I am uncertain about how to capture and manipulate this data within the browser. Presented below is my code snippet ...

Seamless flow from one image to the next

I'm working on a project with a slideshow, but I've noticed that when it transitions between images, it can be quite abrupt. I'd like to find a way for it to change smoothly from one image to the next. <div> <img class="mySli ...

What is the best way to align form elements in the same row using React Bootstrap?

Do you notice how the titles, text boxes, and buttons are all misaligned and messy-looking? How can I make them line up nicely together? I especially want the buttons to anchor themselves at the bottom of this component. I've already tried a few solu ...

Show or hide item by clicking outside the div

Looking for a way to use jQuery's slidetoggle to hide the showup class when clicking anywhere outside of the DIV. Any advice is appreciated! Check out this online SAMPLE: http://jsfiddle.net/evGd6/ <div class="click">click me</div> <d ...

"Discrepancy between Flexigrid's thead and tbody sections

I've run into an issue with using flexigrid in my application. Everything is rendering properly, but when I try to drag a column to resize it, the tbody is not staying in sync with the thead. Check out the image below for reference. Can anyone provid ...

Iterate through several table data cells, extract various data points, and populate an array

I am facing a challenge with two tables on my webpage. The second table is dynamically populated with HTML using JavaScript. To accomplish this, I am checking if the <tr> tags inside the tbody are empty by using the following code: var rowCount = $( ...

Update the DIV using instructions sent from the server

Looking to create a webpage that retrieves data from a mySQL database, specifically a value of 0 or 1. The goal is to have a div on the page automatically refresh with the latest value from the database at set intervals. Additionally, it's important ...

Responsive Bootstrap table unable to expand div upon clicking

My bootstrap responsive table has a unique functionality that allows specific divs to expand and collapse upon button click. While this feature works seamlessly in desktop view, it encounters issues on mobile devices. CSS .expandClass[aria-expanded=true] ...

Keep moving the box back and forth by pressing the left and right buttons continuously

Looking to continuously move the .popup class left and right by clicking buttons for left and right movement. Here is the js fiddle link for reference. This is the HTML code structure: <button class="right">Right</button> <button class="l ...

Activate each division separately with a single script

I am facing an issue where each blue div (<div id="rectangle"></div>) is not firing independently when hovered or clicked. Currently, when I hover/click over the first one, both fire simultaneously. However, if I hover/click over the second on ...

How can the size of the font in a <div> be adjusted based on the number of characters present?

I am attempting to create a basic HTML and CSS layout with two div blocks, each 1000px wide, within a parent container that is 3000px wide. <div class="blocks"> <div class="block-a">text 1</div> <div class="block-b">text 2& ...

Tips for displaying a Rails action without a layout in html format using Ajax

Is it possible to render the new action without the application layout and without altering the current code structure? class FoobarController < ApplicationController def new @foobar = Foobar.new end # ... end When a user clicks on = link_ ...

`Apply event bindings for onchange and other actions to multiple elements loaded via ajax within a specific div`

My form includes various input fields, dropdowns, and text areas. Upon loading, jQuery locates each element, sets its data attribute to a default value, attaches an onchange event, and triggers the change event. The issue arises when some dropdowns are d ...

What is the best way to horizontally align and center the navigation menu?

I've been struggling to center and align the navigation links inside this div horizontally. I attempted a few methods, but none seem to work. I managed to fix the previous issue with #centermenu, but unfortunately it still isn't functioning as e ...

Implementing AJAX to dynamically update the href of the edit path

On my Bookings show page, there is a next button implemented with ajax to navigate through a user's bookings and update their attributes. However, I am looking for a way to dynamically modify the edit and cancel paths for each individual booking on th ...

Utilize a single JavaScript script to handle numerous HTML forms within the same webpage

I am currently facing an issue with a page that contains multiple forms needing the same JavaScript code. This specific code is designed to add more input fields to the form, which it does successfully. However, the problem lies in the fact that it adds in ...