jQuery append item to every div + display it's ID

212 views Asked by At

I am trying to append a button to every div with a certain class, my code so far is:

HTML:

<div id="865" class="gw-gopf-isotope-item">
 <div class="gw-gopf-post-overlay-inner">
  // button goes here
 </div>
</div>

jQuery:

$( ".gw-gopf-isotope-item" ).each(function() {
 var gallid = $(this).attr('id');
 $('.gw-gopf-post-overlay-inner').append('<a class=\"gw-gopf-btn gw-gopf-post-overlay-btn thickbox\" href=\"#TB_inline?width=600&height=550&inlineId=gallery-\"+gallid+\"\">View Photos</a>');
});

The way it works is:

  • user creates a gallery in an admin
  • these are displayed on the frontend
  • another script I wrote creates a thickbox of content unique to each gallery
  • the button is meant to link to that unique thickbox

The append code works fine but it doesn't generate the unique ID for each link hence why I think I need to use the each function?

I have to do this with jQuery as it's amending a pre-built system which I can't modify to add the code in directly.

Any help is really appreciated

1

There are 1 answers

5
mahatmanich On

Since you are using ' as a dilimiter and escaping quotations \", you are missing two times ' around '+gallid+'

It should be:

$('.gw-gopf-post-overlay-inner').append('<a class=\"gw-gopf-btn gw-gopf-post-overlay-btn thickbox\" href=\"#TB_inline?width=600&height=550&inlineId=gallery-'+gallid+'\">View Photos</a>');

If you are still not getting an id debug it.

You can see if the gallid is generated by sending it to the console with console.log(gallid); within the .each loop

$( ".gw-gopf-isotope-item" ).each(function() {
 var gallid = $(this).attr('id');
 console.log(gallid);
...

});

Look at this fiddle:

https://jsfiddle.net/a4zh87jg/4/ This one is correct with your code!