2

I would like to know what is the difference between these two jQuery selectors:

  • $("span")
  • $("<span>")

I know that the former is used to select all elements of the provided HTML tag type in the page (which is specified in the jQuery Element Selector documentation). I am not sure what the latter selector does.

Apologies if this question is a duplicate. If so, please kindly post the URI of the duplicated question.

ecbrodie
  • 11,246
  • 21
  • 71
  • 120

2 Answers2

2
$("span") //Finds all span
$("<span>") //Create a span element 

See this answer : jQuery document.createElement equivalent?

Community
  • 1
  • 1
Akhil Sekharan
  • 12,467
  • 7
  • 40
  • 57
1

The first goes out and finds all existing span elements. The second creates a new span element, wrapped in a jQuery object.

$("span").css("color", "red"); // Make all current <span> elements red
$("<span>").text("Foo").appendTo("body"); // Create new <span>, add to <body>

Optional Second Arguments

Both can take a second argument as well. In the case of the first, the second argument is the context:

$("span", "#foo"); // Becomes $("#foo").find("span");

In the case of the second, the second argument is an object-literal consisting of properties:

$("<span>", { 
    "html": "This is the HTML", 
    "class": "newSpan"
}).appendTo("body");

This is similar to calling the individual methods to set html and attributes:

$("<span>")
    .html("This is the HTML")
    .attr("class", "newSpan")
    .appendTo("body");
Sampson
  • 265,109
  • 74
  • 539
  • 565