javascript - Change color of an element based on it's content -
i use wordpress create web page , used plugin called weekly class schedule. creates timetable, technically it's made table. limitation of plugin can have 1 color of table cell when there , entry.
now, using javascript, how can change color of background, when know example content of td
element constant text?
an example of 1 td element's class name wcs3-cell wcs3-hour-row-10-00 wcs3-day-col-1 wcs3-abs-col-0
dynamically created can't rely on exact names.
i assume wcs3-cell
basic class name below code doesn't work:
function f_color() { if (document.getelementbyclassname('wcs3-cell').value = 'boks') { document.getelementbyclassname('wcs3-cell').style.background-color = "yellow"; } } f_color();
could please advise how fix this? also, should use yellow !important
new css value make sure new code used?
you have several issues in code:
- you should use
==
when comparing values. getelementbyclassname
shouldgetelementsbyclassname
- note 'elements'td
elements not havevalue
property - need readtextcontent
.getelementsbyclassname
returns multiple elements, need loop on each 1 , check values individually.- when using css style name property of
style
object, should use js notation, in casebackgroundcolor
.
with said, try this:
function f_color() { var elements = document.getelementsbyclassname('wcs3-cell'); (var = 0; < elements.length; i++) { if (elements[i].textcontent == 'boks') { elements[i].style.backgroundcolor = "yellow"; } } }
as you've tagged question jquery, here's implementation that:
function f_color() { var $elements = $('.wcs3-cell').filter(function() { return $(this).text() == 'boks'; }).css('backgroundcolor', 'yellow'); }
Comments
Post a Comment