2

I've made a script which copies the alt attribute of an image and puts it into a <span>. It also formulates the information divided by a hyphen. It works like a charm, but only with one image.

I would also like to wrap a <div> around the image to prevent unnecessary markup.

Script snippets:

HTML:

<div id="hoejre">
    <p>
         <span class="alignright">
             <img src="tommy_stor.jpg" alt="Name - Title" 
                  width="162" height="219" />
             <span></span>
         </span>
   </p>
</div>

jQuery:

var alt = $("#hoejre p span img").attr("alt");
$('#hoejre p span span')
 .html("<strong>" + alt.replace("-", "</strong> <em>") + "</em>");

Output:

<span class="alignright">
    <img height="219" width="162" alt="Name - Title"                  
         src="tommy_stor.jpg">
        <span>
            <strong>Name</strong><em>Title</em>
        </span>
</span>

How do you I repeat the effect on several images, with different information within?

2 Answers 2

1

I would go for something like...

$(document).ready(function () {
  $('img.some-class').each(function () {
    var self = $(this);

    self.wrap('<div />').after('<span><strong>' + self.attr('alt').replace('-', '</strong> <em>') + '</em></span');
  });
});

Make sure that you assign a common class to those images you want this to work for, and alter "some-class" appropriately.

I wasn't so sure what 'unnecessary markup' you wanted removed, but the above code is a good starting point.

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

1 Comment

Hi Matt I need the seperator "-" to be replaced more than once. How do you do that?? alt="First - Second - Third - Fourth" Thank you in advance... :-)
0

Here is another approach that assumes all the <img> elements are contained in a single element.

$('#box img').each(
  function(index,element){
    // do your magic here for
  }
)

The function inside jQuery.each() would be the same if you used this or Matt's approach. to expand Matt's approach to work with the HTML you provided:

$('span.alignright').each(
  function(index,element){
    var img=$(this).find('img');
    // do your magic here
  }
);

Which approach you take depends on your situation.

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.