A. Rossi A. Rossi - 5 months ago 14
jQuery Question

Javascript select element that has class with max value

I know there is many topics about Jquery selector with regex, but my need is this

I have some div like this :

<div class="some random things rank0">hello</div>
<div class="some things rank1">hello</div>
<div class="things rank1">hello</div>
<div class="some random rank2 things">hello</div>
<div class="random rank2 some">hello</div>
<div class="some things rank3">hello</div>
<div class="some random rank4">hello</div>


I would like a selector for select every div with a
rank > specific_value
but
i can't modify my html.
I know i should use
filter
function, but i'm not very good in jquery/regex. There is my start :

var specific_value = 2;
$.each($("div").filter(function() {
// I need this
// return rank > specific_value
}), function() {
$(this).html("test");
})


Expected result :

<div class="some random things rank0">hello</div>
<div class="some things rank1">hello</div>
<div class="things rank1">hello</div>
<div class="some random rank2 things">hello</div>
<div class="random rank2 some">hello</div>
<div class="some things rank3">test</div>
<div class="some random rank4">test</div>

Answer

I have used simple JQuery/Javascript code to filter out the result. I am also not that much good in Regex:

var specific_value = 2;
$.each($("div").filter(function() {
  var classes = $(this).attr("class").split(" ");
  var matchfound = false;
  for (i = 0; i < classes.length; i++) {
    if (classes[i].indexOf("rank") > -1) {
      var rank = classes[i];
      rank = rank.replace("rank", "");
      rank = parseInt(rank, 10);
      if(rank > specific_value)
        matchfound = true;
    }
  }
  
  return matchfound;
}), function() {
  $(this).html("test");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<div class="some random things rank0">hello</div>
<div class="some things rank1">hello</div>
<div class="things rank1">hello</div>
<div class="some random rank2 things">hello</div>
<div class="random rank2 some">hello</div>
<div class="some things rank3">hello</div>
<div class="some random rank4">hello</div>

Comments