1

I'm having an issue with this.. is the value gets added but only the first h2 tag. What am I missing?

Thanks

My goal is to grab the value of the h2 tag and add the value to the image as an alt and title tag.

Below is my HTML and JS. Here is my jsFiddle File.

HTML

<ul class="list">
  <li>
    <img title="Product" src="/img.jpg" />
    <h2>Blue</h2>
  </li>
  <li>
    <img title="Product" src="/img.jpg" />
    <h2>Red</h2>
  </li>
  <li>
    <img title="Product" src="/img.jpg" />
    <h2>Yellow</h2>
  </li>
</ul>

JS

var imageID = $('.list').find('h2').html();

$("img").attr('title', imageID + ' Product');​

2 Answers 2

4

Try this

$(".list img").each(function() {
    var txt = $(this).siblings("h2").text();
    $(this).prop("alt", txt).prop("title", txt + " Product");
});

DEMO - use Firebug or similar to review

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

2 Comments

This worked. However, how can I add the h2 value to the title attribute & alt and also append custom text to the end of the title attribute on the image? Similar to how i originally had it.. $("img").attr('title', imageID + ' Product');​
Just set the title parameter exactly the same way as you have set the alt - see updated answer
2

try this :

$("img").each(function(){
   $(this).attr('title', $(this).closest("li").find("h2").text()+ ' Product');​
})

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.