如果子div包含某个数据属性,则删除父div

时间:2016-10-26 16:14:26

标签: javascript jquery

因为我动态地这样做,我必须检查主div是否与某个user-id匹配。如果确实如此,那么深入研究并做额外的工作。让我告诉你我在谈论什么。

<div class="col-md-6 user-card-holder" data-user="2">
  <div class="col-xs-2 single-card">
    <div class="house" data-house="hearts" data-value="q">Q-hearts</div>
  </div>
</div>

有许多div's具有类名user-card-holder。我必须使用data-user属性检查具体的一个。现在我要检查的是:

如果div包含data-house,其值为heartsdata-value的值为q,则将该div与其父级一起删除。这里的父级表示div具有班级single-card,而不是user-card-holder

我尝试过使用filter()。也许我在这里做错了。

 $('.user-card-holder[data-user='+ card.user +'] div div').filter(function(){

     var div = $(this).data('house') == card.house && $(this).data('value') == card.number;
      return div.parent()


     }).remove();

我看到的答案显示基于数据属性删除元素,但不是它的父级。

2 个答案:

答案 0 :(得分:2)

我建议:

// this finds all <div> elements with a
// 'data-house' attribute equal to 'hearts' and a
// 'data-value' attribute equal to 'q':
$('div[data-house=hearts][data-value=q]')
  // traverses to the parent of the matching element(s):
  .parent()
  // removes the parent element(s) from the DOM:
  .remove();

或者,如果您正在动态搜索祖先以找到要删除的相应元素,这似乎是重新阅读您的问题的情况:

// finds <div> element(s) with the class of 'user-card-holder'
// and the 'data-user' attribute equal to the value of the 'card.user'
// variable, and finds the descendant <div> element(s) matching
// the selector used above:
$('div.user-card-holder[data-user=' + card.user + '] div[data-house=hearts][data-value=q]')
  // traverses to the parent of the descendant element:
  .parent()
  // removes the parent element of that descendant:
  .remove();

参考文献:

答案 1 :(得分:0)

尝试此功能:

{{1}}

它会找到一个带有班级&用户卡持有者的div。和data-user = {给定id}然后用data-house =&#39; hearts&#39;来查找它的后代。和数据值=&#39; q&#39;并删除其父级。

不过,大卫的答案已经足够了! :)

相关问题