Reputation: 1
I am new to programming and would really appreciate any help. This is also my first post, so please excuse me if I am doing this wrong as well. I have an html page with a table that gets its values from an array function in php. I need to change the text Monday to Red which I can do, but it only formats the first row. Here is what I have
if ($result->num_rows > 0) {
echo "<table><tr><th>Assessor</th><th>Activity</tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row['first_name']. "</td><td id='Activity' class = 'Activity'>" .
$row['Activity']. "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
and here is the JavaScript code:
function changeSubStringColorT() {
var str = document.getElementById("Activity").innerHTML;
var resT = str.replace("Monday", "<span style='color:blue; font-weight:bold' >Monday</span>");
document.getElementById("Activity").innerHTML = resT;
If I change the getElementById it works, but only the first row. If I change to get ElementsBy ClassName it doen nothing.
I have changed the class of the <td class="Activity" but nothing happens. I have no idea where to look or what to do. Thanks alot guys, this site has helped me a lot since I started
Upvotes: 0
Views: 62
Reputation: 28196
If you still want to solve your problem with JavaScript, then the following might help you:
function hilightMondays(sel) {
document.querySelectorAll(sel).forEach(el=>
el.innerHTML=el.innerHTML.replace(/Monday/g,"<span style='color:blue; font-weight:bold'>Monday</span>"));
}
hilightMondays(".activity")
<table><tr><th>Assessor</th><th>Activity</th></tr>
<tr><td>Vivian</td><td class='activity'>On a Monday I go to school. Monday is my fun day!</td></tr>
<tr><td>Tom</td><td class='activity'>Tuesday is the day after Monday.</td></tr>
<tr><td>Richard</td><td class='activity'>Every Monday I am late. I hate Mondays!</td></tr>
<tr><td>Harry</td><td class='activity'>Friday is the best day of the week!</td></tr>
</table>
You don't even need the class attribute above. You can do this by using a CSS selector referencing the second column like this:
hilightMondays("td:nth-child(2)")
Upvotes: 0
Reputation: 642
You would be better to check the variable in php and add a class red if it is 'Monday'. No javascript required.
if ($result->num_rows > 0) {
echo "<table><tr><th>Assessor</th><th>Activity</tr>";
while($row = $result->fetch_assoc()) {
if ( $row['Activity'] == 'Monday' ) $class = "makeRed";
echo "<tr><td>" . $row['first_name']. "</td><td id='Activity' class = 'Activity {$class}'>" .
$row['Activity']. "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
then just in your css
.makeRed {
color:red;
}
Upvotes: 1