Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jQuery to add IDs to elements?

Tags:

jquery

I can't seem to add IDs to the buttons in a jQuery-created dialog. I can select the buttons after the dialog is declared via selectors as follows:

var buttons = $("#dialog").siblings(".ui-dialog-buttonpane").find("button");

but when I try to do:

buttons[0].attr('id', 'someId');

I get:

TypeError: Object #<an HTMLButtonElement> has no method 'attr'

Any suggestions? I don't see anything in the jQuery docs that implies that attr() shouldn't work on buttons.

like image 871
subrama6 Avatar asked Dec 28 '22 08:12

subrama6


1 Answers

Yes:

$(buttons[0]).attr('id', 'someId');

the attr() method is declared on jQuery objects, but buttons[0] gives you a standard DOM object (of type HTMLButtonElement in this case). jQuery objects are augmented arrays of DOM objects, so indexing into them always gives you the original DOM objects.

Since jQuery does not add methods to DOM objects themselves, you must first wrap the DOM object in a jQuery object to access these methods.

EDIT Then again… there is no need to use jQuery at all for this task.

buttons[0].id = 'someId';
like image 122
Tomalak Avatar answered Jan 13 '23 10:01

Tomalak