1

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

4

Try

$('a[target="_blank"]:has(img[alt])').attr('title', function () {
 return $(this).find('img').attr('alt');
});

DEMO - jsfiddle

Reference

:has()

.attr()

.find()

[ ] has-attribute-selector

answered Nov 9, 2013 at 11:10
1
  • Thanks for your time, but I should target only links which has target="_blank" like <a href="/images/img1.jpg" target="_blank" ... Commented Nov 9, 2013 at 11:20
1

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'));
});

Demo Fiddle to try

answered Nov 9, 2013 at 11:29
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.