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.

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your time, but I should target only links which has target="_blank" like <a href="/images/img1.jpg" target="_blank" ...
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

Comments

Your Answer

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.