0

Problem : I have list in HTML, 5 li > a inside ul and I created array in JS such as :

var list= [
{
    date: "02.2013",
    name: "First",
    icon: "fa fa-heart"
},
{
    date: "05.2014",
    name: "Second",
    icon: "fa fa-flask"
},
{
    date: "03.2012",
    name: "Third",
    icon: "fa fa-gavel"
},
{
    date: "06.2015",
    name: "Fourth",
    icon: "fa fa-graduation-cap"
},
{
    date: "08.2017",
    name: "Fifth",
    icon: "fa fa-trophy"
}];

and i want to add "ICON" content as classes to a. Result should be sth like that :

                 <ul>
                    <li>
                        <a href="#"  class="fa fa-heart"  aria-hidden="true"></a>
                    </li>
                    <li>
                        <a href="#"  class="fa fa-flask" aria-hidden="true"></a>
                    </li>
                    <li>
                        <a href="#"   class="fa fa-gavel" aria-hidden="true"></a>
                    </li>
                    <li>
                        <a href="#"  class="fa fa-graduation-cap" aria-hidden="true"></a>
                    </li>
                    <li>
                        <a href="#"  class="fa fa-trophy" aria-hidden="true"></a>
                    </li>
                </ul>

I can display in console every "ICON" in table, same with "a" but I have no idea what should be next step

How can I take these "classes" from array and put it inside links?

for / foreach ??

I ask for hints, not for solutions - thanks for every comment bros

2
  • Do you truly want to use javascript as the tag show? or are you open to JQuery? It is much less code jquery Commented Jan 6, 2018 at 0:40
  • You can use .classList (an array) or className (a string) to add classes to elements using JS Commented Jan 6, 2018 at 0:44

2 Answers 2

1

A JS solution:

var html_content = "<ul>";
for (var i=0; i<list.length; i++){
    html_content += '<li><a href="#"  class="'+list[i]['icon']+'"  aria-hidden="true"></a>';
}
html_content+= "</ul>";
Sign up to request clarification or add additional context in comments.

Comments

0

Get a collection of the links, loop over them, and add the corresponding classes from the array.

var links = document.querySelectorAll("li > a");
var len = Math.min(links.length, list.length);
for (var i = 0; i < len; i++) {
    links[i].className = list[i].icon;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.