0x1gene
0x1gene

Reputation: 3458

How to convert a string to HTMLElement using jquery?

I wonder how to convert a string to an HTMLElement ?

I have tryed :

$('<i data-icon="'+icon+'" class="smiley-big"></i>')

But in console it shows type: [object Object] If I log existing ellements in the Dom like this:

$('[class^="smiley"]').each(function(){
     console.log(this);
});

I get [object HTMLElement]

Thanks for your help

Upvotes: 0

Views: 1056

Answers (2)

Ozerich
Ozerich

Reputation: 2000

$('<i data-icon="'+icon+'" class="smiley-big"></i>').get(0)

Upvotes: 1

Joseph
Joseph

Reputation: 119837

Because a jQuery object is an array-like object which contains all the selected elements. In this case, it contains only one element, and that is the one you just created. Thus, we can access it via index 0:

var newI = $('<i data-icon="'+icon+'" class="smiley-big"></i>')[0];

In the case of each, it iterates over the object and returns each item as this in the function, which in your case, is your newly created HTML element.

Upvotes: 1

Related Questions