Question

I am rather new to JQuery & Javascript so I need a little help with a piece of code in JQuery that I am trying to write. What I want to do is to write a function that looks through all images in a certain post in Wordpress and checks to see if they have alt="watermark".

If they do then I want to wrap <div> around each <img>. In addition I want to place a second image inside that <div> on top of the other image. I have managed to create the div around the images based on the alt. I have also been able to add an image on the existing one inside that div. However I am not able to repeat that last action. My code only adds image into the first <div>.

$(document).ready(function(){
$("img[alt*='watermark']").wrap('<div id="watermark" />');  
$('#watermark').prepend("<img src='images/watermark.png'/>");
});
Was it helpful?

Solution

You can use before() to add an image before the current image :

$(document).ready(function(){
    $("img[alt*='watermark']").wrap('<div id="watermark" />');
                              .before("<img src='images/watermark.png'/>");
});

This selector:

$('#vannmerke_hvit')

indicates an ID, and ID's are unique, so that only works for one element, the first one. You could change it to a class to make it work with multiple elements.

Lykke til!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top