I have this markup:
<div>
<span id="01">
</div>
<div>
<span id="02">
</div>
i need to add some id for the div
element by their span child, i try it with jquery but something is worng...
$('div').each(function(){
$(this).attr('id', $(this).find('span').attr('id'));
})
Thx for help.
I have this markup:
<div>
<span id="01">
</div>
<div>
<span id="02">
</div>
i need to add some id for the div
element by their span child, i try it with jquery but something is worng...
$('div').each(function(){
$(this).attr('id', $(this).find('span').attr('id'));
})
Thx for help.
Share Improve this question asked Jun 14, 2013 at 9:20 LukasLukas 7,75420 gold badges79 silver badges127 bronze badges 4-
2
id should be unique in a document, so try
$(this).attr('id', 'parent-' + $(this).find('span').attr('id'));
– Arun P Johny Commented Jun 14, 2013 at 9:22 - 1 the id attribute should be unique, meaning you shouldn't have the same id on more than one element. are you getting any console errors? you are missing a ";" at the end of the .each(), might cause it. Also id cannot be a number, it has to start with a letter. – ninja Commented Jun 14, 2013 at 9:23
- Have you tried debugging? – thomaux Commented Jun 14, 2013 at 9:27
- I checked on safari and actually works on chrome and nothing happens, but after some corretcs it's fine.. – Lukas Commented Jun 14, 2013 at 9:31
2 Answers
Reset to default 5Your example seems to work fine. However id's should be unique, so I would suggest:
$('div').each(function(){
$(this).attr('id', 'div-' + $(this).find('span').attr('id'));
});
I also assume you're running your example after page load event.
I just tested your code in Safari 6. It works. I would like to say that setting the id identical to the ID of the span is not a good idea because IDs should be unique.
Also, what's not working for you?
I know this should probably be a ment but I can't ment yet (too low reputation)