Append to all images that follow the id

So, I’d like to add content after every image that follows the id #Image-gallery.

I feel like I am so close, but can’t get it to work. I’ve tried multiple things, but I just can’t figure it out. #Help #Thx

<section id="Image-gallery">
 
      <img src="Brian_in_Canyon.jpg"  /> 
      
      <img src="Brian_in_Canyon.jpg"  /> 
      
      
      
   </section>



<script>

$(document).ready(function(e) {
    
	$("<p>Test</p>").appendTo("#Image-gallery, img");

	
});
</script>

It’s not clear what you are trying to do—at least to me.

I want to add a paragraph after every image in the section that has an id of #Image-gallery

Doesn’t seem very practical to be doing this with JS. Is there a reason why you are looking at this option? The text won’t be in the HTML, which isn’t great from a search engine point of view etc.—so doing this with JS is a last resort kind of option.

Anyhow, you can easily target each image and place content after it with JS, but how are you going to differentiate the content from one image to another? One option would be to extract the alt text from each image and paste it into a paragraph below the image, but your code doesn’t have alt text currently. And if you can change that, then you should be able to add paragraphs into the HTML.

This is what I’m trying to do.

  1. Have posts in wordpress appear in that section (only images will be in the post)
  2. Add the SAME text after each image
  3. Use that text on hover over. The text will actually say, “View Larger Image”
  4. The reason that I’m using jQuery instead of CSS to accomplish this is because I don’t know of a way to adjust the background that goes over the image on hover to be responsive.

First issue: all IDs in the DOM must be unique. You can probably do this with a CLASS instead of ID, though.

There is only 1 ID. It is 1 ID for that section that contains all of the images.

Don’t use appendTo() as that inserts an element INSIDE an element. You want to use .insertAfter().


$("<p>Testing..</p>").insertAfter($("#Image-gallery").find('img'));

Excellent! That worked perfectly. I guess I need to keep becoming familiar with more jQuery methods.

I’ve been working with jQuery for two years, and I will never stop learning. There is so much to jQuery. It is a constant, organic learning process. :slight_smile:

BTW… I would be remiss if I didn’t mention that if you have control over the img tags, it would be easier to give them a classname and .insertAfter(); on the classname.

That seems like extra work though??

It depends. If the image tags are being pulled from a database and you control the output, it would be simple to insert " class=‘classname’" into the image tags.