rhysclay rhysclay - 7 months ago 23
Javascript Question

jQuery find first element of class with unique id

I have a list of elements which is something like this:

<article id="post-647" class="brand-search-result brand-alaffia hidden"></article>
<article id="post-647" class="brand-search-result brand-alaffia hidden"></article>
<article id="post-647" class="brand-search-result brand-alaffia hidden"></article>

<article id="post-650" class="brand-search-result brand-alter-eco hidden"></article>
<article id="post-650" class="brand-search-result brand-alter-eco hidden"></article>
<article id="post-650" class="brand-search-result brand-alter-eco hidden"></article>


Now what I want to is find the first of each unique id and remove the hidden class. This is what I have in jquery so far:

(function(){
$("[id^=post-]").each(function(){
$(this).first(".brand-search-result").removeClass('hidden');
});
})();


Only problem is this running on every article element which makes sense. Any suggestions?

Answer

Store somewhere the information of the unique post. Skip future ones.

var processedPosts = {};

(function(){
$("[id^=post-]").each(function(){
    var id = $(this).prop("id") //modify to use unique ids (as suggested in comments)

    if (!processedPosts[id]) {
        $(this).first(".brand-search-result").removeClass('hidden');
        processedPosts[id] = true;
    }
});

})();