Reputation: 3
My app has a HTML structure like this:
<h2 class="milestone font-md bold my-3 ml-md-3 ml-5 my-md-5">2018</h2>
<h2 class="milestone font-md bold my-3 ml-md-3 ml-5 my-md-5">2017</h2>
And I want to append my HTML template under related class via jQuery. E.G.
<h2 class="milestone font-md bold my-3 ml-md-3 ml-5 my-md-5">2018</h2>
<div>2018 content</div>
<h2 class="milestone font-md bold my-3 ml-md-3 ml-5 my-md-5">2017</h2>
<div>2017 content</div>
First of all, get my parent class data:
var array = $('.timeline__section h2').map(function () {
return $.trim($(this).text());
}).get();
Then I used jQuery.inArray function:
if (jQuery.inArray(year, array) === 1) {
console.log("yes");
}
Its working.
But now, I need append my HMTL template under related class. Tried this trick but its not working good. (Appended my HTML everywhere, not related area.)
if (jQuery.inArray(year, array) === 1) {
$($(".timeline__section h2").text(this)).append("<div class=\"col-10 col-md-6 col-lg-4 d-flex align-items-stretch\">"");
}
What's the problem and what is the right way for this goal?
Upvotes: 0
Views: 37
Reputation: 21489
The .append()
method insert content to the end of element, but you need to insert content after element. So use .after()
$('.timeline__section h2').after(function () {
return "<div>year content</div>";
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="timeline__section">
<h2 class="milestone font-md bold my-3 ml-md-3 ml-5 my-md-5">2018</h2>
<h2 class="milestone font-md bold my-3 ml-md-3 ml-5 my-md-5">2017</h2>
</div>
Also if you have custom data for every year, use bottom code
var data = {
2018: '2018 content',
2017: '2017 content'
}
$('.timeline__section h2').after(function () {
var year = $(this).text().trim();
if (data[year] != undefined)
return "<div>"+data[year]+"</div>";
});
var data = {
2018: '2018 content',
2017: '2017 content'
}
$('.timeline__section h2').after(function () {
var year = $(this).text().trim();
if (data[year] != undefined)
return "<div>"+data[year]+"</div>";
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="timeline__section">
<h2 class="milestone font-md bold my-3 ml-md-3 ml-5 my-md-5">2018</h2>
<h2 class="milestone font-md bold my-3 ml-md-3 ml-5 my-md-5">2017</h2>
<h2 class="milestone font-md bold my-3 ml-md-3 ml-5 my-md-5">2016</h2>
</div>
Upvotes: 1