aschmid aschmid - 2 years ago 91
Javascript Question

wordpress check html class with php or jQuery

I want to check the class of the html (there are posts and every category got a own class for background color) and then set the background.
I wanted to to it with jQuery but it doesn't work because the first one is true so all get the same background.

My php code:

<div class="grid" >
<?php $args = array(
'post_type' => 'post');
$query = new WP_Query( $args );
while ($query->have_posts()) : $query->the_post() ; ?>
<div class="post grid-item <?php foreach((get_the_category()) as $category) { echo $category->cat_name; } ?>" style='background: url("<?php if (has_post_thumbnail()) { the_post_thumbnail_url(); } ?>"); background-color:<?php ?>' >
<h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1>
<?php endwhile;
wp_reset_query(); ?>

my jQuery code that doesn't work

//post background
var back_engagement = jQuery('.grid div').hasClass('engagement');
var back_unternehmen = jQuery('.grid div').hasClass('unternehmen');
var back_forum = jQuery('.grid div').hasClass('forum');

if (back_engagement){
jQuery('.grid-item').css({"backgroundColor": "#959595"});
else if (back_unternehmen) {
jQuery('.grid-item').css({"backgroundColor": "#96A306"});
else if (back_forum) {
jQuery('.grid-item').css({"backgroundColor": "#215270"});

For me it doesn't mater if the solution is with php or jQuery

Answer Source

You can set the CSS property based on simple selector.

jQuery('.grid div.engagement').css({"backgroundColor": "#959595"});
jQuery('.grid div.unternehmen').css({"backgroundColor": "#96A306"});
jQuery('.grid').css({"backgroundColor": "#215270"});

However I would recommend you to set them using classes in CSS

.engagement{ background-color: #959595;}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download