Fredrik
Fredrik

Reputation: 635

Add CSS class based on ID

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 
    } 
}
?>

Upvotes: 0

Views: 5266

Answers (3)

Jon
Jon

Reputation: 437336

First of all your jQuery selector is wrong, you probably meant something similar to

$("#<?php echo $p['id']; ?>.pFavorite").addClass("active");

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

$("#<?php echo $p['id']; ?>").addClass("active");

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

if(array_search($p['id'], explode(",", $_COOKIE['cookie']))) {
    // Use htmlspecialchars for all HTML output; you may need to specify
    // additional parameters (see the function documentation)
    printf('<a href="#" class="active pFavorite" id="%s">IMG HERE</a>',
           htmlspecialchars($p['id']));
}

Upvotes: 4

Gabriel Santos
Gabriel Santos

Reputation: 4974

Why not:

<?php
foreach($statement as $p) {
    if(array_search($p['id'], explode(",", $_COOKIE['cookie']))) {
        echo('<a href="#" class="pFavorite active" id="' . $p['id'] . '">IMG HERE</a>');
    } 
}
?>

?

Upvotes: 0

Andreas Linden
Andreas Linden

Reputation: 12721

<?php
foreach($statement as $p)
{
    if(array_search($p['id'], explode(",", $_COOKIE['cookie'])))
    {
    ?>
    <script type="text/javascript">
        $(document).ready(function() {
            $("#<?php echo $p['id']; ?>.pFavorite").addClass("active");
        });
    </script>
    <a href="#" class="pFavorite" id="<?php echo $p['id']; ?>">IMG HERE</a>
<?php 
    } 
}
?>

Upvotes: -1

Related Questions