user1032531
user1032531

Reputation: 26281

jQuery create element containing child element

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?

Upvotes: 3

Views: 6029

Answers (3)

Mathieu Labrie Parent
Mathieu Labrie Parent

Reputation: 2596

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

Upvotes: 1

LorDex
LorDex

Reputation: 2636

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

Upvotes: 11

LiamWilson94
LiamWilson94

Reputation: 458

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.

Upvotes: 1

Related Questions