0

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!

Deduplicator
  • 41,806
  • 6
  • 61
  • 104
hellomello
  • 7,510
  • 33
  • 121
  • 258
  • 1
    If you're getting the ID of one element and using it to set the ID of another, you must modify it so they are unique, or remove the originating element. You can't have duplicate IDs on a page. – user113716 Jun 10 '11 at 19:10
  • I would not do this. It is very bad form to have multiple elements with the same id. – daybreaker Jun 10 '11 at 19:12
  • This was just an example for simplicity.I just wanted to make it as clear as possible, and I definitely will have to modify it. Thank you guys! – hellomello Jun 10 '11 at 19:33

3 Answers3

4
$("#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);
Jeff
  • 13,117
  • 9
  • 51
  • 93
  • I'm actually using a class for reference and then use the id for my imageID. Thanks! – hellomello Jun 10 '11 at 19:27
  • You're allowed to have many classes on an HTML element as long as they are separated by spaces. `
    ` is perfectly valid markup.
    – Jeff Jun 10 '11 at 19:32
1

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

SLaks
  • 800,742
  • 167
  • 1,811
  • 1,896
1

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

genesis
  • 48,512
  • 18
  • 91
  • 118