GermanMan
GermanMan

Reputation: 103

Jquery: Add IMG Alt text from H1

All products have an H1 for header and I want to use that text for the alt text of the IMG.The script I wrote doesn't work. Can someone help me to get it right. SAMPLE of a single product is below more will be on a single page.

HTML

<li class="prod">
<div class="mainpic">
      <div class="popup">
          <ul class="data">
             <li>feature 1</li>
          </ul>
      <p>SKU: 4430757</p>
</div>

<img src="images/products/4330-12534-9126-333-TQ.jpg" width="220" height="210" 
alt="Some text" /> 
</div>

<h1>Avia  '5571' Women's Running Shoe</h1>
</li>

Script (is this correct?):

var $target = null; 
var $newtext = null; 

$(".prod").each (function () { 

var target = $(this);

var newtext = target.find("h1").html();

target.each ( function () { 

$(this).find(img).attr(newtext);

});

    });

Thanks in advance!

Upvotes: 1

Views: 456

Answers (3)

Richard Dalton
Richard Dalton

Reputation: 35793

$('li.prod').each(function() {
    $('img', this).attr('alt', $('h1', this).text());
});

Upvotes: 0

Joseph Marikle
Joseph Marikle

Reputation: 78530

var $target = null; 
var $newtext = null; 

$(".prod").each (function () { 
    var target = $(this);
    var newtext = target.find("h1").html();
    target.find(img).attr("alt",newtext);
});

That should do it. You already defined target as the current element. no need to use .each on it.

Upvotes: 0

Eric
Eric

Reputation: 97601

$('li.prod').each(function() {
    var img = $(this).find('img');
    var h1 = $(this).find('h1');
    img.attr('alt', h1.text());
});

Or shorter:

$('li.prod').each(function() {
    $(this).find('img').attr('alt', $(this).find('h1').text());
});

Upvotes: 3

Related Questions