I wonder how I can add a CSS class to a link based on the ID in the link, with jQuery. I wan’t to add the CSS class “active” to the link if the if-statement is true. Not that I dont want to remove “pFavorite” from class in link if the statement is true, I just want to add active to, like this class=”pFavorite active” Im not that in to jQuery yet. I hope my code still explains what I want to achieve.
<?php
foreach($statement as $p)
{
if(array_search($p['id'], explode(",", $_COOKIE['cookie'])))
{
?>
<script type="text/javascript">
$("#<?php echo $p['id']; ?>", ".pFavorite").addClass("active");
</script>
<a href="#" class="pFavorite" id="<?php echo $p['id']; ?>">IMG HERE</a>
<?php
}
}
?>
First of all your jQuery selector is wrong, you probably meant something similar to
The above will match the element with the specific id and the class pFavorite, while your original selector would match all elements with the class pFavorite and then look for the element with the specified id inside any of those, not finding anything (because the target element is one of those having the class, not a descendant).
Second, you don’t need a class selector since you are already using an id selector and ids are meant to be unique. So that would be further simplified to
Finally: why do you want to set the class after the page loads with jQuery, when you have all the information you need on the PHP side? You can simply do