I would be very grateful for some guidance or even a solution!
From an array of class names, I'm generating icon sets using a for loop:
// icon array
var iconsArray = ['fa-search','fa-toggle-up','fa-link'];
var iconsArrayLength = iconsArray.length;
// loop through array
for (var i = 0; i < iconsArrayLength; i++) {
// result
console.log('<i class="fa' + ' ' + iconsArray[i] + '"></i>');
}
I also have a navigation element. The list has the same number of items with an ID:
<nav>
<ul id="nav">
<li><a href="">link 1</a></li>
<li><a href="">link 2</a></li>
<li><a href="">link 3</a></li>
</ul>
</nav>
Q. How do I append / prepend the returned icon sets to the correct nav item?
To be clear, the first array value is intended for the first navigation item and so on.
I'm sure there's something out there to answer this question, but the mighty G just doesn't seem to want to serve it up to me!
Thanks in advance.
In response to comment...
The resulting list would look like this:
<nav>
<ul id="nav">
<li><a href=""><i class="fa fa-search"></i>link 1</a></li>
<li><a href=""><i class="fa fa-toggle-up"></i>link 2</a></li>
<li><a href=""><i class="fa fa-link"></i>link 3</a></li>
</ul>
</nav>
You don't even need the for loop
$('#nav li').each(function(i) {
$(this).append('<i class="fa' + ' ' + iconsArray[i] + '"></i>')
})
You can do it like this:
var iconsArray = ['fa-search', 'fa-toggle-up', 'fa-link'];
$('#nav li a').append(function(i) {
return '<i class="fa ' + iconsArray[i] + '"></i>';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link data-require="font-awesome@*" data-semver="4.3.0" rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" />
<nav>
<ul id="nav">
<li><a href=""></a></li>
<li><a href=""></a></li>
<li><a href=""></a></li>
</ul>
</nav>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With