user2170685
user2170685

Reputation: 13

How do I call a jquery function for a dynamic ID?

I need to call a function on click for a image that has a dynamic ID. How do I do it. I am new to JQuery. I have seen other posts that are related to calling a function using the ID but I can't find one that has a dynamic ID.

Anyone know if this is possible?

Upvotes: 0

Views: 3497

Answers (4)

Sam Hanley
Sam Hanley

Reputation: 4755

Assuming you know what the dynamic ID is going to be, then you can just make a string of whatever the ID is and pass that to the jQuery selector. So say that you wanted to dynamically select a bunch of divs with the IDs div1 ... divn:

for(var i = 1; i <= n; i++) {
    $element = $('#div' + i);
    // do whatever to the element
}

Using jQuery's selector, you're just passing it a string, so you can create that string however you want. Now if you don't KNOW the dynamic ID, then there's obviously no way to select something by ID.

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

Create a crazy unique class name and attach it to it.

HTML

<div id="randomgeneratedid" class="crazyuniqueclassname"></div>

jQuery

$('.crazyuniqueclassname').click(function() {
    // Your Code
});

Upvotes: 0

cwohlman
cwohlman

Reputation: 773

If you mean you have a variable with the id name you can simply pass the variable to jquery, prefixed with a hash:

function highlightDiv(id) {
    $("#" + id).addClass("highlight");
}

Upvotes: 0

Jane S
Jane S

Reputation: 1487

If you mean that the ID of the element is not necessarily known, you could give it a specific class and reference it by that instead.

HTML:

<div id="Canbeanything" class="wellknownclassname"></div>

jQuery:

$('.wellknownclassname').click(function() {
    // do whatever
});

Upvotes: 2

Related Questions