Which is the different between property and attribute?

A property is in the DOM; an attribute is in the HTML that is parsed into the DOM.

HTML Attributes

Syntax:

<body onload="foo()">

DOM Properties

Syntax:

document.body.onload = foo;

Using jQuery

If we have:

<!-- HTML -->
<input class-gns="brand">
// jQuery
$("input").attr("data-gns"); // return "brand"
$("input").prop("data-gns"); // return "undefined" because it is not in the DOM.
// It's trying to get [HTMLInputElement].data-gns

See a real example:

Upload a file with jQuery without opening a new page

ajax-with-jquery

In this example we are going to upload a file to our url using AJAX with jQuery.

// We need to select the file in our form before pressing submit   
$("#form-import")
    .submit(function(e) {
        $.ajax({
            url: "/upload/file.txt",
            type: "POST",
            data: new FormData(this),
            processData: false,
            contentType: false
        }).done(function() {
            dialogmessage.show($._("File uploaded"));
        }).fail(function() {
            dialogmessage.show($._("Fail uplading the file"));
        });
        e.preventDefault(); // Avoid launch new page
    });

Here if you want you can download my AJAX logo and use it for free: AJAX logo

You don’t need jQuery any more!

bye-jquery

jQuery used to offer a easy and quick compatible development through all browsers. It avoids dealing with browsers which didn’t support the W3C standard like Internet Explorer. However, nowadays with current updated browsers you don’t need jQuery anymore. Instead of jQuery you should use directly JavaScript.

// jQuery
$(element).html(string);
// JavaScript
element.innerHTML = string;

You can check a great jQuery use comparation with different versions of IE at HubSpot made by Zack Bloom and Adam F Schwartz: YOU MIGHT NOT NEED JQUERY

Anyway, if you still need jQuery (old projects/dependencies) and you want to have a ~5-10k modular library that downloads and executes fast with a familiar and versatile API, you can try Zepto, a minimalist JavaScript library for modern browsers with a largely jQuery-compatible API. If you use jQuery, you don’t need to learn Zepto, just change jquery.min.js for zepto.min.js and that’s all.

Sort by table content

table

How can you sort any HTML table using jQuery?

Element 40
Element 2
Element 29
Element 28
Element 5

Suppose you only want to use the number.

  1. First we must sort elements
  2. After that we have to keep going deleting each element and appending again to the table with the new order
// JS
$("table tr").sort(function (a, b) {
    var a_num = $(a).children(":first-child").text().split(" ")[1];
    var b_num = $(b).children(":first-child").text().split(" ")[1];
    return parseInt(a_num) - parseInt(b_num);
}).each(function(){
    var elem = $(this);
    elem.remove();
    $(elem).appendTo("table > tbody");
});

See a real example:

Edited: improved and without jQuery.