Reputation: 23
I've got a page with multiple div elements of class 'container', ie:
<div class="container">
<div class="data">
<a class="myclass" href="foo" origin="internal"> 123456789 </a>
</div>
<div class="actions">
<button class="save" role="add" add="Save" remove="Remove"> Save </button>
<button class="delete" role="add" remove="Discard" rel="nofollow"> Discard </button>
</div>
</div>
How can I select all buttons of class 'delete', but only if the a element had origin="internal"?
The common ancestor of both elements is the div of class "container".
Besides, how can I programmatically click on all those buttons on page load?
Upvotes: 0
Views: 71
Reputation: 1698
You can select all the buttons with class="delete"
and then you can use an if else statement
. For example:
$('.delete').on('click',function(){
if($(this).parent().data('origin') == 'internal'){
//do something
}else{
//do something else
}
})
Upvotes: 1
Reputation: 184607
Filter and map all containers:
const result = Array.from(document.querySelectorAll(".container"))
.filter(c => c.querySelector("a[origin=internal]"))
.map(c => c.querySelector("button.delete"));
console.log(result);
<div class="container">
<div class="data">
<a class="myclass" href="foo" origin="internal"> A </a>
</div>
<div class="actions">
<button class="save" role="add" add="Save" remove="Remove"> Save </button>
<button class="delete" role="add" remove="Discard" rel="nofollow"> Discard A </button>
</div>
</div>
<div class="container">
<div class="data">
<a class="myclass" href="foo" origin="external"> B </a>
</div>
<div class="actions">
<button class="save" role="add" add="Save" remove="Remove"> Save </button>
<button class="delete" role="add" remove="Discard" rel="nofollow"> Discard B </button>
</div>
</div>
<div class="container">
<div class="data">
<a class="myclass" href="foo" origin="internal"> C </a>
</div>
<div class="actions">
<button class="save" role="add" add="Save" remove="Remove"> Save </button>
<button class="delete" role="add" remove="Discard" rel="nofollow"> Discard C </button>
</div>
</div>
(Furthermore, i believe that jQuery should never be used.)
Upvotes: 0