user2894296 user2894296 - 28 days ago 5
HTML Question

Appending link element within list element dynamically

With using jquery I need to create a element to be added inside a

<li>
which has its own content. Final result should be like below

<li> Hello <a> user! </a> Welcome! </li>


So far I have tried out below.

var list = $('<li></li>');
var link = $('<a></a>');
link.innerHTML = "user!";
list.append(link);


But this will give an output like below.

<li> <a> user! </a> </li>


How can I include 'hello' and 'welcome' on the either side of
<a>
?

Answer

You can do something like this.

console.log(
  $('<li/>', {
    html: [
      document.createTextNode(' Hello'),
      $('<a> user! </a>'),
      document.createTextNode('Welcome! ')
    ]
  })[0].outerHTML
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>