选择编号大于50的所有元素项

时间:2016-07-18 20:01:16

标签: javascript jquery html

有许多div class="element-item"。我想选择所有带有.element-item的{​​{1}}和使用jQuery大于50的class="number"的div。

<div class="element-item one " data-category="one">
    <h3 class="name">Mercury</h3>
    <p class="symbol">Hg</p>
    <p class="number">30</p>
    <p class="weight">200.59</p>
</div>
<div class="element-item two " data-category="two">
    <h3 class="name">Mercury</h3>
    <p class="symbol">Hg</p>
    <p class="number">60</p>
    <p class="weight">200.59</p>
</div>
<div class="element-item two " data-category="three">
    <h3 class="name">Mercury</h3>
    <p class="symbol">Hg</p>
    <p class="number">80</p>
    <p class="weight">200.59</p>
</div>

2 个答案:

答案 0 :(得分:2)

您可以使用.filter()过滤带有value > 50

的div

var divs = $('.element-item .number').filter(function(){
  return parseInt($(this).text()) > 50;
});

//add a specail class
divs.each(function(){
        $(this).addClass('special') 
});

console.log(divs.length);
.special {
 background-color: #eee;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="element-item one " data-category="one">
  <h3 class="name">Mercury</h3>
  <p class="symbol">Hg</p>
  <p class="number">30</p>
  <p class="weight">200.59</p>
</div>
<div class="element-item two " data-category="two">
  <h3 class="name">Mercury</h3>
  <p class="symbol">Hg</p>
  <p class="number">60</p>
  <p class="weight">200.59</p>
</div>
<div class="element-item two " data-category="three">
  <h3 class="name">Mercury</h3>
  <p class="symbol">Hg</p>
  <p class="number">80</p>
  <p class="weight">200.59</p>
</div>

答案 1 :(得分:0)

你可以使用jquery each()函数。

for case case:

$(".element-item").each(function(){
     if(parseInt($(this).find(".number").html()) > 50){
          // This is .element-item div with number greater Than 50!
          // Try to alert its name
          alert($(this).find(".name").html());
     }
}