I need to place html in a javascript string. Specifically, I would like to add an HTML link to a div tag with javascript.
html:
<div id="mydivtag"></div>
javascript:
document.getElementById('mydivtag').innerHTML = "<li><a href=\"someLink\">Some Link</a></li> ";
Am I formatting the html link I am adding through javascript correctly?
I need to place html in a javascript string. Specifically, I would like to add an HTML link to a div tag with javascript.
html:
<div id="mydivtag"></div>
javascript:
document.getElementById('mydivtag').innerHTML = "<li><a href=\"someLink\">Some Link</a></li> ";
Am I formatting the html link I am adding through javascript correctly?
Share Improve this question edited Aug 14, 2021 at 18:45 Patrick Beynio 8581 gold badge8 silver badges15 bronze badges asked Apr 30, 2012 at 9:54 user840930user840930 5,57822 gold badges68 silver badges98 bronze badges 6- 2 Does it work when you execute your code? – Amberlamps Commented Apr 30, 2012 at 9:56
- if its works u coded correctly – user1347312 Commented Apr 30, 2012 at 9:57
- Yes you do, but you can use single quotes or nodes (document.createElement, appendChild) – user1150525 Commented Apr 30, 2012 at 9:57
- in case you don't know about rendering html template, you should check handlebarsjs.. it'd make your process more robust and simpler to maintain later :) – Tzu ng Commented Apr 30, 2012 at 10:01
- I get the error message: Open quote is expected for attribute "href" associated with an element type "a". – user840930 Commented Apr 30, 2012 at 10:17
3 Answers
Reset to default 10Looks fine and works here. You may want to consider mixing single quotes instead of escaping the double quotes, but that's just a preference.
document.getElementById('mydivtag').innerHTML = "<li><a href='someLink'>Some Link</a></li>";
You can have it in one line:
document.getElementById("mydivtag").appendChild(function(li, l, t) { li.appendChild(function(a, l, t) { a.href = l; a.innerHTML = t; return a; } (document.createElement("a"), l, t)); return li; } (document.createElement("li"), "mylink", "mytext"));
It needs more jQuery:
$('#mydivtag').html('<li><a href="someLink">Some Link</a></li>');