Home > OS >  get a javascript object as a link
get a javascript object as a link

Time:12-29

I need your help; i want the name obtained from the json array to be a link; that is, once I get the name I click on it to be directed to a page (for example, it is assumed www.google.com). To do this I used the following line:

document.getElementById("demo").innerHTML = " myObj["name"] ";

but I get nothing. Can anyone help me please?

const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = "<a href='http://www.google.com'> myObj["
name "] </a>";
<h2>Access a JavaScript Object</h2>
<p id="demo"></p>

CodePudding user response:

document.getElementById("demo").innerHTML = "<a href='http://www.google.com'>" myObj['name'] "</a>";

or

document.getElementById("demo").innerHTML = `<a href='http://www.google.com'>${myObj["name"]}</a>`;

CodePudding user response:

Use template literals

<html>
<body>

<h2>Access a JavaScript Object</h2>
<p id="demo"></p>

<script>
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = `<a href='http://www.google.com'>${myObj["name"]}</a>`;
</script>

</body>
</html>

  • Related