codeEnthusiast codeEnthusiast - 5 months ago 10
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

<a>
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="http://www.stackoverflow.com">
Button
</div>

<div id="my-button2" class="button-style-1" data-href="http://www.w3schools.com">
Button 2
</div>


and jQuery:

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


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

$('#my-button[i]')


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?

Answer

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

Your example with an update: https://jsfiddle.net/fLj7y0kz/1/

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)`.