Search code examples
javascriptjqueryhtmlcss

Filter elements in a DOM with common 'class' name and apply CSS on it - JQuery


In a DOM, I could filter out elements having class names starting with a particular word, here it is answer_list_two cpts_ and the result is given below.

$('[class^="answer_list_two cpts_"]') =>

[<div class=​"answer_list_two cpts_1_19234">​…​</div>​, <div class=​"answer_list_two cpts_2_19234">​…​</div>​, <div class=​"answer_list_two cpts_3_19234">​…​</div>​, <div class=​"answer_list_two cpts_4_19234">​…​</div>​, <div class=​"answer_list_two cpts_5_19234">​…​</div>​, <div class=​"answer_list_two cpts_1_19234">​…​</div>​, <div class=​"answer_list_two cpts_2_19234">​…​</div>​, <div class=​"answer_list_two cpts_3_19234">​…​</div>​, <div class=​"answer_list_two cpts_4_19234">​…​</div>​, <div class=​"answer_list_two cpts_5_19234">​…​</div>​, <div class=​"answer_list_two cpts_1_19235">​…​</div>​, <div class=​"answer_list_two cpts_2_19235">​…​</div>​, <div class=​"answer_list_two cpts_3_19235">​…​</div>​, <div class=​"answer_list_two cpts_1_19235">​…​</div>​, <div class=​"answer_list_two cpts_2_19235">​…​</div>​, <div class=​"answer_list_two cpts_3_19235">​…​</div>​]

from this, I would like to take an element, find its class name, find another element having same class name, compare the height of both the DIV elements and apply the larger height value to both the DIV elements.

How can I write the jQuery code for implementing the same?


Solution

  • Try

    var filtered = {}, $els = $('.answer_list_two[class*="cpts_"]');
    $els.each(function () {
        var clazz = this.className.match(/cpts_\d+_\d+/)[0];
        if (filtered[clazz]) {
            return;
        }
    
        var height = 0;
        $els.filter('.' + clazz).each(function () {
            var h = $(this).height();
            if (height < h) {
                height = h;
            }
        }).height(height);
        filtered[clazz] = true;
    })
    

    Demo: Fiddle