Robert
Robert

Reputation: 10400

creating new elements with jQuery

I was reading the basic documentation on using jquery at: http://learn.jquery.com/using-jquery-core/manipulating-elements/

In the section titled, "Creating New Elements", there is a second example which is as follows:

// Creating a new element with an attribute object
$( "<a/>", {
    html : "This is a <strong>new</strong> link",
    "class" : "new",
    href : "foo.html"
});

I do not understand this completely.

  1. How is it that you are creating an element with invalid html as: the 'a' followed by the forward slash?

  2. I have never seen an "html" attribute ever in my life.

Any explanations to this example would be helpful.

Upvotes: 1

Views: 125

Answers (3)

SomeShinyObject
SomeShinyObject

Reputation: 7821

Self Closing <a />

Back when the 'new HTML' was being thought of (before HTML5), Web Developers decided that the next HTML should model after XML. So, XHTML was born. One of the markup conventions in XML is the self-closing tag, for tags that are just there to be there or only contain attributes. We still see this convention in modern HTML to this day. While some tags require an ending, like our <a> tag here, other don't like a <br> or an <img> tag, thus when XHTML became popular the new "cool" convention was to self-close and yell at people in forums who didn't do the same thing you were doing. That's all she wrote on that. Technically, it's the same as <a></a>.

HTML attribute

This isn't an attribute of the <a> element, but a property of the jQuery object that is created with $('<a />'). It's equivalent to the html() method of the jQuery library. It just assigns the innerHTML property of the element.

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324820

<a/> indicates a tag with no content, otherwise known as a self-closing tag. Content is then added to it.

jQuery interprets attempting to set an html attribute as setting the link's content HTML.

That being said, the code is kinda butt-ugly. I would much prefer this:

var a = document.createElement('a');
a.className = "new";
a.href = "foo.html";
a.innerHTML = "This is a <strong>new</strong> link";

Or, for bonus points, remove that innerHTML line and replace it with:

a.appendChild(document.createTextNode("This is a "));
a.appendChild(document.createElement('strong')).appendChild(document.createTextNode("new"));
a.appendChild(document.createTextNode(" link"));

Upvotes: 3

WynandB
WynandB

Reputation: 1427

<a/> is merely a self-closing tag and it could just as easily be rewritten to be $("<a></a>") instead.

The value of the html property is what jQuery uses to ultimately set the inner HTML content.

Upvotes: 3

Related Questions