How to add text from span tag to data-attr?
Example:
I have this code
Here is an example that should work for you. There is probably a few ways you can pull this off, but this should hopefully get you started. Please see the attached JSFiddle to see this example in action
$(function() {
$('[title*="icon"] span').each(function(){
$(this).parent().closest('div').attr('data-attr', $(this).text())
});
});
Here is another way you can do this as well
$('[title*="icon"]').each(function(){
$(this).attr('data-attr', $(this).children().closest('span').text());
});
Your <div>
s should have attribute title="icon"
You are using a callback to attr()
function, so return the value which you need to set inside the function using .text()
.
$(document).ready(function () {
$("[title='icon']").attr('data-attr', function () {
return $(this).find('span').text();
}).removeAttr('title');
});
Demo