2

Using some js object like

links = {
    link1: "Text1",
    link2: "Text2",
    link3: "Text3"
};

I want to create several <a> elements with href from keys and content from values, like

<a href="link1">Text1</a>
<a href="link2">Text2</a>
<a href="link3">Text3</a>

What is the best and the shortest way to do it using js or some popular js frameworks?

2 Answers 2

2

you want to use for loop in javascript.

HTML:

 <p id="demo" />

JS:

links = {
    link1: "Text1",
    link2: "Text2",
    link3: "Text3"
};

var element, filling = "";
for (element in links) {
    filling += "<a href=\"{0}\">{1}</a>"
        .replace("{0}", element)
        .replace("{1}", links[element]);
}

document.getElementById("demo").innerHTML = filling;

See the demo here: http://jsfiddle.net/0subxy9m/1/

Sign up to request clarification or add additional context in comments.

Comments

2

with Angular for example and your links object

HTML

<li ng-repeat="(link,text) in links">
    <a href="http://example.com/{{link}}">{{text}}</a>
</li>


JS

$scope.links = {
  link1: "Text1",
  link2: "Text2",
  link3: "Text3"
};

plnkr demo here

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.