Strip White Space From Element Using JQuery

January 7th, 2015  | Categories: Drupal, Drupal 7, JavaScript, JQuery

PROBLEM
I don’t think I’m going to explain this very well. Here’s a short story long.

So what I was trying to do was kind of confusing as it is. I’ll try to explain… In Drupal 7 there is a cool module called field group table. I needed this module to display data in a table format. However, one of the limitations of this module is that it doesn’t display the label in the th for grouped elements. So say you have an address that you’d like to display in a table. You can use this module but it won’t display the group name in the th. It’ll go above the information.

The "location" text and "CRS Coordinator" text is above the data and not in the t h

I used some slick JQuery to move the “Location” text inside the empty th like so:

$(".table_site_map_info .group_table td #site_map_location_th div span").first().appendTo(".table_site_map_info .group_table th.field-label-hidden:eq(0)");

That did the trick. However I noticed that there was a space added and the “Location” and “CRS Coordinator” didn’t line up correctly with the “Phone” (which isn’t a group).

The "location" and "CRS coordinator" were moved to the t h but there was a space before them which doesn't align

SOLUTION
Unfortunately the JQuery trim function needs a parameter and all the examples on JQuery and around the web always had it using a JavaScript variable. I just needed to trim elements; not variables.

So in other words, I wanted to do something like $(“.table_site_map_info .group_table th”).trim() . However that didn’t work.

I had to go back tho the drawing board kind of. I first got it out of its span (which I thought initially was the spacing problem). I used:

$(".table_site_map_info .group_table th span").contents().unwrap();

This didn’t work. It got rid of the span but it still had the space. After looking at the HTML in FireBug, I saw an added space in the th. I needed to remove the space. Unfortunately, like I said earlier, the trim function was useless. I had to individually set each HTML element to its trimmed self.

So, here’s my code:

$(".table_site_map_info .group_table th.field-label-hidden:eq(0)").text($.trim($(".table_site_map_info .group_table th.field-label-hidden:eq(0)").text()));

Sorry that this is a long post and it’s mostly useless but I hope it can help someone. I wanted to post this to remember it.

a screen shot of what it's supposed to look like

If anyone has a more efficient way to do all the above using JQuery or Drupal, I’d love to hear it.

No comments yet.

TOP