sdfor
sdfor

Reputation: 6438

What does a JQuery selector on HTML markup do?

I noticed that

  $( "<a></a>" ).text( "wow" );

will put the text "wow" inside the a tags and result in

<a>wow</a>

I can't find this documented. Where else can I use this? Is it only available within text()?

Upvotes: 1

Views: 364

Answers (4)

Fr&#233;d&#233;ric Hamidi
Fr&#233;d&#233;ric Hamidi

Reputation: 262919

That is indeed documented. It's the second form of the $() function.

The code in your question creates a new <a> element, then sets its inner text to wow. You can create DOM element trees from arbitrary HTML markup that way, and all the jQuery methods, not only text(), can be called on the resulting object.

Upvotes: 3

Alnitak
Alnitak

Reputation: 339796

It's not a selector, it's an element creator.

Putting valid HTML instead $() creates that HTML. The call to .text() thereafter is of course separate, and changes the inner content of the just-created element.

Upvotes: 1

VulgarBinary
VulgarBinary

Reputation: 3589

It is actually parsing the HTML element and then applying the text operation to it.

You would be able to do the same thing with any html string, take for instance:

$("<input type='text' value='Hello World!' />").val() will return Hello World.

The selector will parse any HTML passed, this is how you can take a standard click event and apply $(this) which is a selector on the containing HTML element that the event was fired on.

Hope this clarifies your confusion!

Upvotes: 1

rcravens
rcravens

Reputation: 8390

The

$("<a></a>") 

returns a jQuery object and you can call most of the jQuery functions. For instance you can do this:

$("<a></a>").attr("id","anchor1").css({color:"#ff0000"}).appendTo("#parent");

You can simplify this a bit by just doing

$("<a>").

Upvotes: 2

Related Questions