Question

I'm trying to use an element by its ID without explicitly creating a reference to it.

http://jsfiddle.net/D8A8P/

<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"
Was it helpful?

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"));
});

DEMO

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top