spiderplant0
spiderplant0

Reputation: 3952

What is this: $('<div />')

In a tutorial I came across this jQuery:

var encodedName = $('<div />').text(name).html();

I havent seen the '<div />' before. Doesnt look like a CSS selector. Any ideas?

Upvotes: 1

Views: 138

Answers (5)

Suresh Atta
Suresh Atta

Reputation: 122018

I slightly differs if you say, selector.

That is Jquery Html attribute

If a string is passed as the parameter to $(), jQuery examines the string to see if it looks like HTML (i.e., it starts with <tag ... >). If not, the string is interpreted as a selector expression, as explained above. But if the string appears to be an HTML snippet, jQuery attempts to create new DOM elements as described by the HTML.

Ex

$( "<p id='test'>My <em>new</em> text</p>" ).appendTo( "body" );

Upvotes: 5

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382274

This simply isn't a selector at all but some HTML

var encodedName = $('<div />').text(name).html();

is equivalent to

var encodedName = $('<div></div>').text(name).html();

or

var encodedName = $('<div>').text(name).html(); // HTML fragments are automatically closed

It builds a jQuery element from some HTML, gives it some text, and then gets the innerHTML.

The purpose of this code is obviously to encode a string as HTML. For example

console.log($('<div>').text("3 < 4").html());

logs

"3 &lt; 4"

Upvotes: 4

Reactgular
Reactgular

Reputation: 54801

The output of a $(...) jQuery selector is always a reference to a Document element (or a zero length collection). In order for that to be true. It will construct DOM elements in memory to satisfy this requirement.

So $('<div>') returns a reference to jQuery where a DIV element has been selected, but is not in the DOM. jQuery has created it in memory only.

You can then append this to the current document, like so;

$('<div>').appendTo('body');

You can also perform selection on the returned object, like so;

$('<div><span class="stuff"></span></div>').find('.stuff').html("<span>something else</span>");

Upvotes: 1

Raidri
Raidri

Reputation: 17550

<div /> is an empty div element. With $('<div />') you create an empty div element as jquery object (not yet in the DOM / on the page) which you can then manipulate and later insert into your page if you wish.

Upvotes: 2

Tommi
Tommi

Reputation: 3247

This construction creates new jQuery object which contains one div element. It can be slightly shorter though: $("<div>")

Upvotes: 3

Related Questions