Using jQuery to prepend HTML before selected images -


i'm looking prepend html before images have been defined via variable named 'products'.

in context - idea add special offer text product images if have been defined sale items (the products listed in 'products' variable).

i'm there offer text being prepended multiple times instead of once each. i'm assuming it's use of each statement i'm not sure it's falling over:

html:

<ul class="product-list">   <li><img src="https://i.imgur.com/jdtk2xh.png"></li><!-- targetted -->   <li><img src="https://i.imgur.com/rfew1zq.png"></li><!-- targetted -->   <li><img src="https://i.imgur.com/ozq9pfh.png"></li><!-- targetted -->   <li><img src="http://i.imgur.com/eat4hw8.png"></li><!-- not targetted -->   <li><img src="https://i.imgur.com/8gsrqeg.png"></li><!-- targetted --> </ul> 

jquery:

$(function() {     /*products we're targetting*/     var products = ["jdtk2xh", "rfew1zq", "ozq9pfh", "8gsrqeg"];    $.each( products, function( key, value ) {     /*for each product found add class*/         $('ul.product-list li img[src*="' + value + '"]').addclass('special_offer_image');               /*on each product class add something*/         $( "<p>test</p>" ).insertbefore( "img.special_offer_image" );      }); }); 

jsfiddle link: https://jsfiddle.net/9ucqdg2e/9/

where going wrong?

problem area $( "<p>test</p>" ).insertbefore( "img.special_offer_image" ); create new p , inserted before every selector.

you need reference of img , perform insertion using it.

$.each(products, function(key, value) {     //get reference of img element      var img = $('ul.product-list li img[src*="' + value + '"]');     //add class     img.addclass('special_offer_image');     //insert     $("<p>test</p>").insertbefore(img); }); 

updated fiddle


or, use

$.each(products, function(key, value) {     $('ul.product-list li img[src*="' + value + '"]').addclass('special_offer_image');          });  //move outside each() $("<p>test</p>").insertbefore('img.special_offer_image'); 

Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -