Alberto De Caro
Alberto De Caro

Reputation: 5213

Getting the default(?) element of a jQuery() selection

I am sure there is a simple solution.

The starting scenario was the following. I create a <select> element and populate it dynamycally:

function CreateDropDown(name, id, optionList)
{
    var combo = $("<select></select>").attr("id", id).attr("name", name);

    $.each(optionList, function (i, item) {
        combo.append("<option value='"+item.val+"'>" + item.el + "</option>");
    });

    return combo;
}

The aim was to extract the outerHTML. The following works right:

combo[0].outerHTML();

But I feel that indexing the array is very rough. At least in all that cases where the jQuery() function return a single element array.

Question

Whenever the jQuery() function return a single element array, is it possible to get the unique element without array indexing?

Demo

Upvotes: 1

Views: 101

Answers (3)

Engineer
Engineer

Reputation: 48803

If you "feel that indexing the array is very rough", you could write your own nice helper method. Something like a:

window.$$ = function(){
   return jQuery.apply(jQuery,arguments)[0];
}

Usage:

var combo = $$("<select></select>");
console.log( combo.outerHTML );

Upvotes: 2

Nikola Radosavljević
Nikola Radosavljević

Reputation: 6911

jQuery objects are inherently collections of DOM objects, and there is no syntactic way to treat a jQuery object as wrapper around a single item.

jQuery documentation suggests using get method to access individual DOM elements. It does not comment on performance difference between indexing operator and .get(), but it does say that "each jQuery object also masquerades as an array", so it would be ok to assume that indexing operator just adds another method call.

Upvotes: 3

Declan Cook
Declan Cook

Reputation: 6126

Use .get() to get the html elements.

http://api.jquery.com/get/

Upvotes: 1

Related Questions