Since, I'm doing this dynamically, I have to check whether the main div matches a certain user-id
. If it does, then dive into it and do the extra work. Let me show you what i'm talking about.
<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>
There are many div's
having the classname user-card-holder
. I have to check the specific one with the data-user
attribute. Now what I'm checking is:
If a div contains data-house
with the value of hearts
and also data-value
with the value of q
, then remove that div along with it's parent. Here parent means the div
having the class single-card
and not the user-card-holder
I have tried using filter()
. Maybe I'm doing something wrong here.
$('.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();
I have seen answers which shows to remove the element based on data attribute, but not it's parent.
I'd suggest:
// 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();
Alternatively, if you're searching an ancestor dynamically to find the appropriate element(s) to remove, which seems to be the case on a re-reading of your question:
// 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();
References:
Try this function:
removeCardFromUser(2);
function removeCardFromUser(id) {
$('.user-card-holder').filter(function(){
var user = $(this).data('user');
if (user === id) {
$(this).find('div').filter(function(){
var house = $(this).data('house');
var value = $(this).data('value');
if (house === 'hearts' && value === 'q') {
$(this).parent().remove();
}
});
}
});
}
It looks for a div with class 'user-card-holder' and data-user = {given id} and then looks for its descendants with data-house = 'hearts' and data-value='q' and deletes its parent.
David's answer would suffice though! :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.