Reputation: 1761
I'm struggling to get my syntax correct to correctly append an anchor inside a list item with the structure I'm working with.
The structure that I have to append into is below;
CURRENT OUTPUT
<ul class="q_circles_holder five_columns no_line">
<li class="q_circle_outer">
<a href="/the-potential-centre" target="_self">
<img src="/test.img">
</a>
<div class="q_circle_text_holder">
<h3 class="q_circle_title" style="">The Header Text</h3>
</div>
</li>
</ul>
I need to create a function that will loop through every list item inside the un-ordered list and place an anchor link (using the already stated href ) So ideally my desired output would then read -
DESIRED OUTPUT
<ul class="q_circles_holder five_columns no_line">
<li class="q_circle_outer">
<a href="/the-potential-centre" target="_self">
<img src="/test.img">
</a>
<div class="q_circle_text_holder">
<h3 class="q_circle_title" style="">The Header Text</h3>
<a href="/the-potential-centre" target="_self">Learn More</a>
</div>
</li>
</ul>
I have this currently, but its not working correctly
NOT WORKING CODE -
$('.q_circles_holder').find('li').each(function(idx) {
var $this = $(this),
str = '<a class="learn-more" target="_self" href="' + $this.find('a').attr('href') + '">Learn More</a>';
$this.append(str);
});
Any help would be greatly appreciated.
Thanks,
D
Upvotes: 1
Views: 242
Reputation: 1546
Here we go. Working fiddle here: https://jsfiddle.net/sjpszy4e/.
Javascript
$('.q_circles_holder').find('li').each(function() {
$(this).append('<a class="learn-more" target="_self" href="' + $(this).find('a').attr('href') + '">Learn More</a>');
});
HTML
<ul class="q_circles_holder five_columns no_line">
<li class="q_circle_outer">
<a href="/the-potential-centre" target="_self">
<img src="/test.img">
</a>
<div class="q_circle_text_holder">
<h3 class="q_circle_title" style="">The Header Text</h3>
</div>
</li>
<li class="q_circle_outer">
<a href="/the-potential-centre2" target="_self">
<img src="/test.img">
</a>
<div class="q_circle_text_holder">
<h3 class="q_circle_title" style="">The Header Text 2</h3>
</div>
</li>
</ul>
Upvotes: 0
Reputation: 3324
$('.q_circles_holder').find('li').each(function() {
var $this = $(this);
var href = $this.find('a:eq(0)').attr('href');
$this.find('h3').after("<a href='"+href+"' target='_self'>Learn More</a>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="q_circles_holder five_columns no_line">
<li class="q_circle_outer">
<a href="/the-potential-centre" target="_self">
<img src="/test.img">
</a>
<div class="q_circle_text_holder">
<h3 class="q_circle_title" style="">The Header Text</h3>
</div>
</li>
</ul>
Upvotes: 1
Reputation: 381
Replace $this.append(str)
with $this.find('.q_circle_text_holder').append(str)
Upvotes: 0