1

I have dynamically created articles on my page within a div with an id #content. The articles have a long string of classes, for example

<article id="post-126" class="post-126 post type-post status-publish format-standard hentry category-all-portfolio category-detached portfolio_post target">

and

<article id="post-125" class="post-125 post type-post status-publish format-standard hentry category-all-portfolio category-terraced portfolio_post">

I want to add an additional class to these articles, ONLY IF it contains a certain class. For example, if the article contains the class "category-detached" (which the first one does) I want to add a class "target" to it.

Here is what I have tried, but it won't work

$(document).ready(function(){

if($('#content article').hasClass('category-detached')){
    $(this).addClass('target'); 
}
});

2 Answers 2

3

this in your case is window and not the element.

Just do:

var $elem = $('#content article');
if($elem.hasClass('category-detached')){
    $elem.addClass('target'); 
}

or

   $('#content article').addClass(function(){
        if($(this).hasClass('category-detached')) return "target";
   });
Sign up to request clarification or add additional context in comments.

2 Comments

+1, but technically, he could have that entire function wrapped in a function, and is calling it like Method.call($), thus changing this.
@BradM True but probly an overkill but he can make use of addClass Callback as well. I liked your solution as well if OP doesn't want to do anything else in the condition your first one would be simplest way to do.
2

The simplest solution.

$('#content article.category-detached').addClass('target'); 

The reason it doesn't work is because this isn't being referred to the context of your element.

If you switched it the following, it would modify this to refer to each element of your collection.

$('#content article').each(function() {
    if($(this).hasClass('category-detached')){
        $(this).addClass('target'); 
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.