kal
kal

Reputation: 23

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

Upvotes: 1

Views: 40

Answers (2)

Barmar
Barmar

Reputation: 782683

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>

Upvotes: 1

Dekel
Dekel

Reputation: 62676

The div element you just created still exists (while inside the function) - but it's not part of the DOM of the document (unless you used append to add it to the DOM).

Note that the garbage collector of javascript will probably delete that DOM node because after that function there will be no reference to that DOM element, so it is not needed anymore.

Upvotes: 1

Related Questions