brianray
brianray

Reputation: 1169

jquery simplify selection for onclick event

Something looks wrong (inefficient?) with:

$($('.feature-s').siblings()).children().children('a[data-target=#deleteModal]').parent().parent().click();

I want to select the span where:

/html/body/div/div/div/div[1][class="feature-s"]
/html/body/div/div/div/div[2]/span/a/i/span <= click

But not where:

/html/body/div/div/div/div[1][class="something else"]
/html/body/div/div/div/div[2]/span/a/i/span <= not handled

I recreated the situations here:

http://jsfiddle.net/brianray/ncu6u/

If my selector is fine, just say so. I just feel like there must be a better way to select that button based on the existing dom.

Thanks!

Upvotes: 3

Views: 101

Answers (3)

Mathew Thompson
Mathew Thompson

Reputation: 56429

The simplest and fastest (out of all the other answers) is:

$('.feature-s + div a[data-target="#deleteModal"]')

See jsperf:

enter image description here

Upvotes: 2

Chris
Chris

Reputation: 44

check the jsFiddle below. You can directly select the elements that come directly after feature-s using the + selector.

$('.feature-s + div').find('a[data-target="#deleteModal"]').click(function(){
    alert('hey');
    return false;
});

The sample below works just fine and is more efficient.

http://jsfiddle.net/ncu6u/1/

Upvotes: 1

Alex Denysenko
Alex Denysenko

Reputation: 134

I think

$('.feature-s').siblings()

already returns jQuery object so you don't have to wrap it into the $().

All in all seems fine. Hope this helps.

Upvotes: 0

Related Questions