ElDiabolo
ElDiabolo

Reputation: 376

Selecting a generated id with jQuery

I have an html element like this:

<div id="myelement_9082173219731721923">

I want to add a class to this element to select it with css. It is loaded after the other stuff on the site, because it´s generated by an external javascript. That´s why I tried:

$('[id^="myelement_"]').load(function()
{
    alert("im here");
    $('[id^="myelement_"]').addClass('myclass');
});

But it doesn´t reach the alert. What am I doing wrong? Thanks

Upvotes: 1

Views: 70

Answers (1)

eisbehr
eisbehr

Reputation: 12452

This should do the work, load on the div element will never happen. Use a DOM change listener instead. And you don't need the quotes around the id selector. It is not wrong, but not a must have.

$("body").on("DOMSubtreeModified", function() {
    $('[id^="myelement_"]').addClass('myclass');
});

Working example.

You should change body to the most smallest selector of your DOM, where the div#myelement_ will be appear. And if it happens only one time, change on to one. Then the listener disables itself and will not run constantly on changes.

Upvotes: 1

Related Questions