Filter elements in the DOM with the common name "class" and apply CSS to it - JQuery

In the DOM, I can filter out elements with class names starting with a specific word, here it is answer_list_two cpts_ , and the result is shown 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>​]

I would like to take an element, find its class name , find another element with the same class name , compare the height both DIV elements and apply a higher height value to both DIV elements. Please help me with jQuery code to implement it. Thanks:)

+6
source share
3 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

+4
source

Take it as a beginning (unproven), let me now, if I have to 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()) } }); }); 
+2
source

You would just do something like comparison:

 function compareHeight($el, $el2){ var h1 = $el.height(); var h2 = $el2.height(); var h = h1 > h2 ? h1 : h2 $el.css('height', h); $el2.css('height', h); } var $items = $('.class'); if($items.length > 1){ compareHeight($items.eq(0), $items.eq(1)); } 

I'm not sure which logic you want to use to get the elements, but select them as you want and pass them to this function, but you want to compare and set the heights as you mentioned.

+1
source

Source: https://habr.com/ru/post/987970/


All Articles