user4383363
user4383363

Reputation:

jQuery click event is affecting all tags with the same class

I'm working with node-horseman and I'm making use of .evaluate() and jQuery to trigger a click function on a button on Google Alerts. It's working, but it's affecting all .delete_button.

Each li has a data-id attribute that has an unique value. It's created by Google Alerts itself, so I took advantage of this to select the correct block with node-horseman, and by testing with .html(), it works nicely, it does select the right block by the given data-id.

jQuery('#manage-alerts-div li').attr('data-id', this.feedID).find('.alert_buttons').html()

The inspected code of the Alert based on the given data-id is the following:

enter image description here

And the returned HTML with the jQuery selection:

<a href="/alerts/feeds/07997923364799863317/3782479325533077987" tabindex="0"><span class="rss_icon" title="RSS"></span></a><span class="edit_button alert_button" title="Edit" role="button" tabindex="0"></span><span class="delete_button alert_button" title="Delete" role="button" tabindex="0"></span>

Then, I try to click on the .delete_button:

jQuery('#manage-alerts-div li').attr('data-id', this.feedID).find('.alert_buttons > .delete_button').trigger('click')

But it insists on affect ALL the present .delete_button class.

Upvotes: 0

Views: 383

Answers (1)

nnnnnn
nnnnnn

Reputation: 150010

If you are trying to select only the element with a specific attribute value, try the attribute equals selector as follows:

jQuery('#manage-alerts-div li[data-id="' + this.feedID + '"]')
  .find('.alert_buttons > .delete_button')
  .trigger('click');

Here's a breakdown of what your existing code does:

jQuery('#manage-alerts-div li')

...selects all li elements in #manager-alerts-div, then

.attr('data-id', this.feedID)

...sets their data-id attribute to whatever this.feedID is, then

.find('.alert_buttons > .delete_button')

...finds elements within the original set of all '#manage-alerts-div li' elements, then

.trigger('click')

...triggers the click handler on all of them.

The testing with .html() that you mentioned may have confused things because .html() returns the content of only the first element in the jQuery object, even if the selector you had used matched many elements, so that might have made it seem like you'd selected only one element.

Upvotes: 1

Related Questions