Dal Dal - 1 year ago 143
jQuery Question

jQuery creating a new element

This might be very noobish to ask but I am very new to jQuery as I realised that I can't avoid it forever.

I need a simple explanation of an example that I am following, I understand the final outcome but I would like to know what each part does.

function example1 (a) {
var i = $('<div />').text(a).html();

$('body').append('<li><strong>' + i + '</strong></li>')
}


So the example creates a new element and appends it to the body as you might have guessed the final outcome.

However, this is where I get confused
$('<div />').text(a).html()
... I know
$('<div />')
creates a new element instead of selecting the existing divs... but when I apply this function to a button click it creates just this part
<li><strong>' + i + '</strong></li>
... What happened to the new div created? also why is the example selecting the
.text(a).html()
and when I remove one or the other of the
.text(a).html()
it all messes up?

I hope this makes sense and thank you in advance :)

Answer Source

The DIV you created becomes inaccessible when the function returns, so it's garbage that can be reclaimed by the GC.

The purpose of using .text(a).html() is to convert the text of a to HTML entities, to prevent cross-site scripting (XSS) attacks. .text(a) sets the text of the DIV, without interpreting a as HTML. Then accessing .html() gets the resulting HTML that produces the same output. E.g. if you call example1('<div>'), it will set i = '&lt;div&gt;'.

This temporary DIV isn't really needed, since you can do the same thing by setting the text if the <strong> element:

function example2(a) {
  $('ul').append(
    $('<li>').append($('<strong>', {
      text: a
    }))
  );
}

example2("item 1");
example2("item <div> 2");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
</ul>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download