In this code, we have an HTML <h1>
element with the id "gender" the user’s . We have defined CSS classes .female
and .male
to specify the color for female and male users, respectively.
<script type= "text/javascript">
// Set the user's gender (either 'male' or 'female')
var gender = 'female';
// Get the HTML element by its id
var userNameElement = document.getElementById('gender');
// Conditionally change the color based on the gender
if (gender === 'female') {
userNameElement.classList.add('female');
} else {
userNameElement.classList.add('male');
}
</script>
<style>
.female {
color: pink;
}
.male {
color: blue;
}
</style>
How might this code be altered after the "gender" setting was changed by the user? I’d want the system to automatically assign the desired color based on whether we’re female or male. ( Because this is not happening now, unfortunately! )
The user’s gender follows from the MySQL database.
<h1 id="gender" class="mt-0 mb-0 text"><?php echo $_SESSION['username']; ?></h1>
<?php echo $_SESSION['gender']; ?>
In JavaScript I’d want to color the users by gender.
3
Answers
Get the value of
gender
from the session variable:The class names matches with the strings of the gender. So doing this should be enough:
Are people really downvoting this question because of identity politics? Regardless of personal opinions this is a valid coding question that could help other people trying to achieve different but similar things.
The interesting thing is that your current code is working correctly on the js/css side of things. I made no changes to your code and get these results:
My guess is that there’s something wrong with how the gender value is being stored on the server side. Maybe there’s a naming typo somewhere, or some kind of caching issue?