Rodrigo Dias Rodrigo Dias - 4 months ago 16
jQuery Question

Copy value of an alt and create a data element with this value with jQuery

How can I copy the value of a 'alt' and turn into a 'data-id' for several sample images (with jQuery):

<img src="" alt='test1' />
<img src="" alt='test2' />
<img src="" alt='test3' />


As should be:

<img src="" alt='test1' data-id='test1' />
<img src="" alt='test2' data-id='test2' />
<img src="" alt='test3' data-id='test3' />

Kld Kld
Answer

You can iterate through all the images with .each() and add an attribute data-id.

$('img').each(function(){
  $(this).attr('data-id', $(this).attr('alt'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="" alt='test1' />
<img src="" alt='test2' />
<img src="" alt='test3' />     

Comments