3

Creating a div element in jQuery does a good job on describing how to create and insert an element, however, I wish to create an element with a child element such as <li><a href="abc.html">click</a></li>. The href and text is susceptible to XSS, so I need take steps. I could create the <a> element like:

var href='abc.html',text='click';
jQuery('<a/>', {
    href: href,
    text: text
}).appendTo('#mySelector');

How do I modify this to include the </li> element?

Community
  • 1
  • 1
user1032531
  • 22,993
  • 61
  • 191
  • 346

3 Answers3

10

wrap it up:

$(document).ready(function() {
  var href='abc.html',text='click';

jQuery('<a/>', {
    href: href,
    text: text
}).wrap("<li>").parent().appendTo('#mySelector');


})

http://codepen.io/anon/pen/Eyqco

LorDex
  • 2,544
  • 1
  • 15
  • 29
2

Personnaly, i like to do it in html directly :

var html = "";
html += "<li>";
html += "<a href='www.google.com' >click me</a>";
html += "</li>";

$("myselector").append(html);
Mathieu Labrie Parent
  • 2,578
  • 1
  • 8
  • 10
1

Firstly you could append the <li> tag to the element with the id mySelector.

$('<li>').appendTo('#mySelector');

Then you append your <a> tag to the li element.

LiamWilson94
  • 438
  • 2
  • 7
  • 24