3

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?

6
  • 2
    Does it work when you execute your code? Commented Apr 30, 2012 at 9:56
  • if its works u coded correctly Commented Apr 30, 2012 at 9:57
  • Yes you do, but you can use single quotes or nodes (document.createElement, appendChild) Commented Apr 30, 2012 at 9:57
  • in case you don't know about rendering html template, you should check handlebarsjs.com. it'd make your process more robust and simpler to maintain later :) 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". Commented Apr 30, 2012 at 10:17

3 Answers 3

10

Looks 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>";
Sign up to request clarification or add additional context in comments.

Comments

1

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"));

Comments

0

It needs more jQuery:

$('#mydivtag').html('<li><a href="someLink">Some Link</a></li>');

1 Comment

it needs less jQuery

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.