codeEnthusiast codeEnthusiast - 10 months ago 46
Javascript Question

Simplify selector with numbered IDs

I have a series of divs on the same page for which I have attached a click function that acts like an

tag, directing the user to a URL extracted from a custom data-attribute. My HTML is as follows:

<div id="my-button1" class="button-style-1" data-href="">

<div id="my-button2" class="button-style-1" data-href="">
Button 2

and jQuery:

$('#my-button1,#my-button2').click(function() {
var dataURL = $(this).data('href');, '_blank');

My question is this, is it possible to simplify the selector to something like:


such that it would be much more compact in the event that I have many of these divs contained on the same page? If it is possible, how would I achieve this effect?


You could use $('div[data-href]') which will apply to any div with a data-href attribute.

Your example with an update:

The typical way I've done it and seen it done is as @arop suggests and use a specific class for those elements and use the class selector $('div.myclass)`.