-3

I'm trying to insert a @HTML.ActionLink element inside a li element using the following code:

    var ul = document.getElementById('container');  
    var enlace = '@Html.ActionLink("Details", "Details", "Elements", new { id = "5" }, null)';

    var li = document.createElement('li');
    li.appendChild(document.createTextNode('My title'));
    li.appendChild(document.createElement('br'));

    ///////////////////////////////////////////////
    li.appendChild(document.createElement(enlace));
    ///////////////////////////////////////////////

    ul.appendChild(li);

Is it possible?

ekad
  • 14,436
  • 26
  • 44
  • 46
  • 1
    You're the one who tried it, you tell us. What exactly is the problem with that code? – Brandon May 12 '15 at 15:25
  • You can nest an anchor element inside of a list element, yes. Whether or not your code successfully does that, we can't know unless you tell us. – David May 12 '15 at 15:28
  • I tried this code but it's not working. The line surrounded by //// does not take effect on the page – Javier Herrera May 12 '15 at 15:31

1 Answers1

0

You're passing an entire HTML element to document.createElement(), which expects only a tag name. Essentially, you're doing this:

document.createElement('<a href="someLink">some text</a>')

whereas the function works like this:

document.createElement('a');

You can probably fix this by separating the creation of the element from the setting of the element's HTML to your custom server-generated HTML. Replacing just the code surrounded by the comments, it might look like this:

///////////////////////////////////////////////
var enlaceElement = document.createElement('a');
enlaceElement.innerHTML = enlace;
li.appendChild(enlaceElement);
///////////////////////////////////////////////

I have a full demo here.

David
  • 208,112
  • 36
  • 198
  • 279