hellomello
hellomello

Reputation: 8585

can i append() or html() into an id attribute within a tag?

I have jquery grabbing an id from something else (image) and I would like to append that id into an input hidden field

var imageID = $('#slides li').find('img').attr("id");

This gives me the id, and I know that if I do something like this :

$("#pic-title").html(imageID);

It will append to <div id="pic-title">(this is where the imageID value will be)</div>.

But what if I want to put into an attribute within a tag?

<div id="(imageID value will be placed here instead)"></div>

I hope this is clear enough. Thank you!

Upvotes: 0

Views: 146

Answers (3)

Jeff
Jeff

Reputation: 14279

$("#pic-title").attr('id', imageID);

This is what you are looking for.

EDIT You should be weary of doing this though. You are creating a duplicate id on two or more HTML elements. This is invalid since ids must be unique. I suspect that most modern browsers would be still able to display the elements just fine but your JavaScript could break or produce unexpected results after duplicating the id.

I would change it up by appending some predefined value to the id:

$("#pic-title").attr('id', imageID + '_title');

or use the class attribute instead:

$("#pic-title").addClass(imageID);

Upvotes: 4

genesis
genesis

Reputation: 50976

Just use $("#old_id").attr('id', 'new_id');

Upvotes: 1

SLaks
SLaks

Reputation: 887413

You can set an attribute by writing $(something).attr('name', value)

Upvotes: 1

Related Questions