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?

3 Answers 3

11

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

Sign up to request clarification or add additional context in comments.

Comments

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.

3 Comments

Thanks LiamWilson. Thought there might be a more direct way to do so.
@user1032531 there is. check my answer ;)
Alternatively, you could wrap the li element around the <a> tag.
1

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

2 Comments

As I indicated, the text ckick me is user provided. This could result in XSS.
..........why tho?`

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.