Question

In advance thank you for any help you offer!

I have the following HTML code:

<div class="ProductImage">
   <a href="URL LINK">
      <img src="IMAGE LINK" alt="BLAH BLAH - SALE!" />
   </a>
</div>
<div class="ProductImage">
   <a href="URL LINK">
      <img src="IMAGE LINK" alt="BLAH BLAH - BONUS!" />
   </a>
</div>

I want, using Javascript, and once the page loads, to find all instances of images inside of DIVs of class ProductImage where the ALT value contains the word "SALE" and change the HTML as follows:

<div class="ProductImage">
   <a href="URL LINK">
      <img src="IMAGE LINK" alt="BLAH BLAH - SALE!" />
   </a>
   <img src="MY NEW SALE IMAGE LINK" class="MyClass" />  <!-- NEW inserted HTML statement -->
</div>
<div class="ProductImage">
   <a href="URL LINK">
      <img src="IMAGE LINK" alt="BLAH BLAH - BONUS!" />
   </a>
   <img src="MY NEW BONUS IMAGE LINK" class="MyClass" />  <!-- NEW inserted HTML statement -->
</div>

I am stuck with referencing child & parent nodes in my various code iterations... insanity is setting in...

Can you help this (almost mad) beginner please.

Thanks in advance! MarcusL

Was it helpful?

Solution

Try

var imgs = document.getElementsByTagName('img'), img, newImg;
var regex = /sale/i;
for(var i = 0; i < imgs.length; i++){
    img = imgs[i];
    if(regex.test(img.alt)){
        var parent = img.parentNode.parentNode;
        newImg = document.createElement('img');
        newImg.src='new-img';
        parent.appendChild(newImg)
    }
}

OTHER TIPS

If you can/are/will use jQuery then it can be done like this:

jQuery('img[alt*="SALE"]').attr('alt', 'BLAH BLAH - SALE!');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top