Try using the attribute starts with selector
,
$("[id^='btn-']").on("click", function (e) {
e.preventDefault();
console.log(this.id);
});
Question
I'm trying to use an element by its ID without explicitly creating a reference to it.
<button id="btn-1">Show Content A</button>
<button id="btn-2">Show Content B</button>
<button id="btn-3">Show Content C</button>
<div id="content-1">Fancy Pants</div>
<div id="content-2">Small Town</div>
<div id="content-3">Cheap Whiskey</div>
If a user clicks on a btn, I want to know which one was clicked.
$( ??? ).on("click", function (e) {
e.preventDefault();
console.log(this.id);
});
// If user clicks on btn-1
// console: "btn-1"
// If user clicks on btn-2
// console: "btn-2"
Solution
Try using the attribute starts with selector
,
$("[id^='btn-']").on("click", function (e) {
e.preventDefault();
console.log(this.id);
});
OTHER TIPS
You can use attribute starts with selector
. Try this:
$("button[id^='btn-']").on("click", function (e) {
e.preventDefault();
console.log($(this).attr("id"));
});
Your example code only shows buttons, so the handler could simply be applied to all buttons:
$('button').on('click', function (e) {
console.log(this.id);
});
A simple selector should be preferred over one that uses [id^=...
because the latter will search the whole document.
$("button[id^='btn-']").on("click", function (e) {
console.log($(this).attr("id"));
});
there is no need to specify preventDefault. botton does not have any default functional action