c.k
c.k

Reputation: 1105

Changing style of all same class name of elements using javascript

I got this error. And I can't find what was wrong with it. I am using PHP and javascript.

I have a hidden iframe below my code:

<iframe id="hidden_form_submitter" name="hidden_form_submitter" style="width:100%;height:1px;visibility:hidden"></iframe>

And I have this line of code, an action button in which the id of a row will send as URL parameter:

<tr bgcolor="#d1ffcf" class="row-<?=$transaction['id']?>">
<td>
    <a class="done-btn" data-confirm="Are you sure?" href="?action=change&status=done&transact_id=<?=$transaction['id']?>" target='hidden_form_submitter' title="Click if matched!"> Done</a>   
</td>
</tr>

Then lastly I have this code on top to update the row in my database:

<?
if($_GET['action'] == 'change'){

    //update query here

    echo "<script>window.parent.document.getElementsByClassName('row-{$get['id']}').style.backgroundColor='green';</script>";

    exit;
}

?>

No problem on the updating side in my server. The problem is the JavaScript wherein I want to change the bgcolor of all same class without reloading the whole page.

UPDATE: Cannot change the background of every class. Example, I have this parameter to be send. ?action=change&status=done&transact_id=1608 So all element with class row-1608 should change the background color or change something style.

Upvotes: 1

Views: 45

Answers (1)

Ethan
Ethan

Reputation: 4375

Try changing this:

echo "<script>window.parent.document.getElementsByClassName('row-{$get['id']}').style.backgroundColor='green';'</script>";

To this:

echo "<script>";
echo "var allRows = window.parent.document.getElementsByClassName('row-{$get['id']}');";
echo "for (var i = 0; i < allRows.length; i++) {";
echo "    allRows[i].style.backgroundColor = 'green';";
echo "}";
echo "</script>";

You need to iterate allRows and set the backgroundColor on each element.

(Inspired by this example)

Upvotes: 1

Related Questions