Creating an element in jQuery 1.4

Creating a new DOM element in jQuery is super easy. Just add the element of your choice into the jQuery “wrapper” and you’re ready! Really simple. This works like a charm for simple elements, but what happens when you want to add multiple attributes, styles, content, or even events on the new element? Unfortunately you have to “chain” many different functions to build the desired element.

jQuery 1.4 is tackling this problem and provides a quick, easy to use and flexible way to create new and more complicated elements, just by passing an object literal with the appropriate details. In other words, trying to make the element construction a more robust and elegant process, rather than a huge chain of functions. But enough theory, let’s have a look at an actual example. Below I’m appending a new div element to the document’s body. The second parameter (object literal) is responsible for adding all these attributes, styles, content and events on the div!

$('<div/>', {  
 id: 'feature',  
 class: 'post',  
 css: {  
border : '1px solid red',  
padding : '5px'  
 },  
 html: '<p>This is a featured <strong>super</strong> post</p>',  
 click: function() {  
alert('You click the featured post!')  
 }  
}).appendTo('body');Check out this Pen!

Not impressed yet? Well get creative! Try the below example and you’ll see what I mean!

$('<input>', {  
type: 'text',  
val: 'text input',  
css: {  
border : '1px solid #000',  
padding : '5px'  
},  
focusin: function() {  
$(this).val('').addClass("active");  
},  
focusout: function() {  
$(this).val('text input').removeClass("active");  
}  
}).appendTo('form');Check out this Pen!

Finally for the spec-junkies have a look at the official documentation.

4 convenient jQuery tips

I just read the last page of the jQuery Cookbook (great book by the way), and I’d like to present 4 very convenient jQuery tips I used to ignore. Better late than ever I guess 😉

Specify a context

By specifying a context, we help jQuery identify the elements we need, and as a result speed up things, especially on larger projects with complicated DOMs. It’s also ridiculously easy to implement. Just pass a second parameter at the jQuery wrapper, for example :

$('h1', 'div#posts'); //using jQuery wrapper as context

// ex.
var title = $('h1', 'div#posts').css('color', 'red');Check out this Pen!

The above example will select all the h1 headers from the div element with an id of “posts”. Our second context parameter is using a typical jQuery selector to refer the context element. We can refer the context in any way we want, using simple CSS expressions or  even DOM references.

$('h1', 'body'); // using an expression
$('input', document.form[0]); // using a DOM reference
Check out this Pen!

Keep this tip in mind because it can really boost up your web apps.

“Chaining” rocks

Just take advantage of the jQuery “chaining” functions! It might feel a little awkward at first, but can save a lot of time and sweat. Below, I’m creating a div element (with an id of “test”), that contains a paragraph element with an anchor node and the text “John”. Then I’m selecting that anchor and passing an attribute (a hypertext reference to be more specific or simply href), then re-selecting my first element (the div) using the end() function, and finally appending everything to the body of the document. Chaining rocks!

$('<div id="test"><p><a>John</a></p></div>').find('a').attr('href' , 'http://phrappe.com/').end().appendTo('body');Check out this Pen!

A good habit is to change lines on each function to increase readability. So the above one-line spaghetti code can be re-written like this :

$('<div id="test"><p><a>John</a></p></div>')
.find('a')
.attr('href' , 'http://phrappe.com/')
.end()
.appendTo('body');Check out this Pen!

Easy, clean, readable…

Select elements based on their content

Yes, it can be done easily using the :contains() filter. The snippet below will select all the paragraph elements that contain the string “Hello”. Keep in mind that the specific filter is case-sensitive, so paragraphs with the text “hello” (lowercase h), won’t be selected…

$('p:contains("Hello")');

// example
$('p:contains("Hello")').css('color' , 'red');Check out this Pen!

Replace DOM elements

I wasn’t aware of this jQuery function. You can use the replaceWith() function and replace the selected elements with new ones! Below I’m selecting all the list items with the “old” class, and replacing them with a new list item. Very convenient.

$('li.old').replaceWith('<li>new li</li>');Check out this Pen!

Well, that’s it for now. If you have any convenient jQuery tips, don’t hesitate to leave a comment below, and of course stay tuned for more…