I have generated html content
<a href="/images/img1.jpg" target="_blank">
<img src="/images/img1.jpg" alt="asdsadasdsa" />
</a>
how can I on dom ready use image alt content (in this case asdsadasdsa) and add new attribute title with alt image content, in other words above html should be
<a href="/images/img1.jpg" target="_blank" title="asdsadasdsa">
<img src="/images/img1.jpg" alt="asdsadasdsa" />
</a>
js should target only code which has target="_blank"
as part of a href attribute.
BobRock
3,4673 gold badges33 silver badges48 bronze badges
asked Nov 9, 2013 at 11:09
2 Answers 2
Try
$('a[target="_blank"]:has(img[alt])').attr('title', function () {
return $(this).find('img').attr('alt');
});
DEMO - jsfiddle
Reference
answered Nov 9, 2013 at 11:10
Tushar Gupta - curioustushar Tushar Gupta - curioustushar
57.2k24 gold badges106 silver badges110 bronze badges
-
Thanks for your time, but I should target only links which has target="_blank" like <a href="/images/img1.jpg" target="_blank" ...user2783193– user27831932013年11月09日 11:20:23 +00:00Commented Nov 9, 2013 at 11:20
You can try with this:
var $target = $('a[target="_blank"]');
var $content = $target.find('img').attr('alt');
$target.attr('title', $content);
or this way:
var $target = $('a[target="_blank"]');
$target.each(function(){
$(this).attr('title', $(this).find('img').attr('alt'));
});
answered Nov 9, 2013 at 11:29
lang-js