user2783193
user2783193

Reputation: 1022

adding html element using js

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.

Upvotes: 1

Views: 82

Answers (2)

Jai
Jai

Reputation: 74738

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

Upvotes: 1

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

Upvotes: 4

Related Questions