user961437
user961437

Reputation:

Is this the correct way to set an id for an element that doesn't have an id yet in jQuery?

$("a[href*='http://www.google.com']").attr('id','newId');

Can only reference it by href.

Upvotes: 0

Views: 62

Answers (1)

Alnitak
Alnitak

Reputation: 339856

Yes, that's the correct way to add an id attribute to an element that doesn't already have one.

However you should ensure that there's only one matching element, as it's incorrect to have two elements with the same ID on a page, e.g.:

$("a[href*='http://www.google.com']").first().attr('id', 'newId');

This would, of course, still leave you with the problem of what to do with the remaining matching elements, if any. A possible solution would be:

$("a[href*='http://www.google.com']").attr('id', function(index, attr) {
    return 'newId_' + index;
});

which will assign the elements the IDs newId_0, newId_1, etc.

Upvotes: 5

Related Questions