如果条件相同,则选择if元素,如果有更多同级元素

时间:2019-02-06 01:04:09

标签: javascript jquery html

如果有更多具有相同类的兄弟元素,我想选择具有相同文本的元素$('。art-h .head-art')

if($('.art-h .head-art').text() == $(this).text()) { ... }

2 个答案:

答案 0 :(得分:0)

这里是使用香草JS和find()方法的示例。

这对您有用吗?

const getArt = (text) => {
  return Array.from(document.querySelectorAll('.head-art')).find(e => e.innerText === text);
};

console.log(getArt('some text'));

console.log(getArt('anoter text'));
<div class="art-h">
  <div class="head-art">some text</div>
</div>
<div class="art-h">
  <div class="head-art">anoter text</div>
</div>
<div class "related-heads">
  <h1 class="rel-head">some text</h1>
</div>

答案 1 :(得分:0)

我相信您需要使用.filter ..试试下一个代码

$('.rel-head').click(function() {
  var el = $(this);
  $('.art-h .head-art').filter(function(){
      return $(this).text().trim() == el.text().trim();
  }).toggle();  // change toggle() with any action you want
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="art-h">
  <div class="head-art">some text</div>
</div>
<div class="art-h">
  <div class="head-art">another text</div>
</div>
<div class="related-heads">
  <h1 class="rel-head">some text</h1>
</div>
<div class="related-heads">
  <h1 class="rel-head">another text</h1>
</div>