Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add css class to a td tag using javascript

i'm trying to make a timetable for a Moodle in form of a Greasemonkey script.

The idea is to highlight the subject for the current hour, but i can't find a working way of doing it.

I'm injecting css into the page, and using jQuery to add the injected css class to the target td.

This is the css code injected into the page header:

.current_class {background-color:green};

And this is the javascript code used to add the class to the td:

var cell = $("#timetable_table").find("tr").eq(current+1).find("td").eq(date.getDay());

I know cell is the correct td because i can cell.text("foo") and the correct cell is modified, but when i do:

cell.addClass("current_class");

the table stays the same.

I don't have to do it that way, i only want to dynamically change the background on a td tag, so i don't mind using other methods.

Thanks.

like image 978
gcq Avatar asked Mar 12 '26 00:03

gcq


2 Answers

First I would suggest you change to this:

var cell = document.getElementById('timetable_table').rows(current+1).cells(date.getDay());

And:

cell.className += (cell.className ? " " : "")+"current_class";

But that's just for performance reasons

The probable cause of the issue is that you have background-color being defined elsewhere with greater specificity. Try using this CSS selector:

#timetable_table tr>td.current_class{background-color:green};

That should be specific enough to win.

like image 116
Niet the Dark Absol Avatar answered Mar 14 '26 15:03

Niet the Dark Absol


use className property for change or add class like example:

tbody.firstChild.lastChild.className='tr-parent1';

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!