Add class with php [duplicate]

3

I have a link.

<a href="contacto.php?id='uno'" class="uno">contacto</a>

I want to know if I can add another class to that link with php, for example.

<a href="contacto.php" class="uno active">contacto</a>

How can I help?

    
asked by Karlos Yalta 20.08.2018 в 18:34
source

3 answers

1

You have several ways to do it, one of them can be like this:

We imagine that the url is www.midominio.es/contacto

<?php
$uri = $_SERVER['REQUEST_URI'];
$newClass = '';
if(preg_match('/^\/contacto/', $uri)){
    $newClass = ' active';
} ?>

Printing between the html

<a href="contacto.php" class="uno<?php echo $newClass; ?>">contacto</a>

Printing within PHP

<?php
//...
echo "<a href=\"contacto.php\" class=\"uno$newClass\">contacto</a>";
//...
?>

Or this one:

<?php
//...
printf("<a href=\"contacto.php\" class=\"uno%s\">contacto</a>", $newClass);
//...
?>

This would be the link that returns any of them:

<a href="contacto.php" class="uno active">contacto</a>
    
answered by 20.08.2018 в 18:47
1

With PHP I know you can not, but you can insert JavaScript and PHP code to add the class, I mean: When you go to redirect to the PHP file you can print a JS code to add the class:

<a href="contacto.php?id=uno" id="contacto" class="uno">contacto</a> <!-- Le agrego un Id para identificarlo con JS -->

Now print this code with PHP:

<script>
   var contacto = document.getElementById("contacto");
   contacto.className += " active";
</script>

Or you can do it through JQuery:

<script>
   $('#contacto').addClass('active');
</script>

It is to remind you that when you print with'echo () 'Code of any type, it takes it as the actual code of the document.

I hope it serves you. Greetings.

    
answered by 20.08.2018 в 18:45
0

You can not do it with PHP from the browser, but with a simple Jquery script using toggleClass or addClass as follows:

<script>
$(document).ready(function(){
 $(".uno").addClass("active");
});
</script>
    
answered by 20.08.2018 в 18:44