Kr0m
Kr0m

Reputation: 23

How to select an element if a condition on a descendant of a common ancestor is met?

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

Answers (2)

Dean Gite
Dean Gite

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

brunnerh
brunnerh

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

Related Questions