Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Please help me with the JQuery code for implementing the same. Thank you :)

like image 980
Rajesh Omanakuttan Avatar asked May 27 '15 03:05

Rajesh Omanakuttan


2 Answers

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

like image 51
Arun P Johny Avatar answered Oct 03 '22 01:10

Arun P Johny


Take this as start (unproved), let me now if I should change something.

var classs;
$('[class^="answer_list_two cpts_"]').each(function(index, val) {
    classs = val.attr('class');
    $('.'+classs).each(function(index2, val2) {
        if(val.height() > val2.height()){
            val2.css('height', val.height());
        } else {
            val.css('height', val2.height())
        }
    });
});
like image 41
lmgonzalves Avatar answered Oct 03 '22 01:10

lmgonzalves