Tuesday, January 13, 2015

JQuery Best Practices - DOM Manipulation


  Usually we folllow like this ..

 // Set's an element's title attribute using it's current text
  $(".container input#elem").attr("title", $(".container input#elem").text());

  // Set's an element's text color to red
  $(".container input#elem").css("color", "red");

  // Makes the element fade out
  $(".container input#elem").fadeOut();

This is fine if ..

If you like repeating yourself
If you do not care about performance
If you don't care about best practices

  Best Approach.. 

  // Stores the live DOM element inside of a variable

  var elem = $("#elem");

  // Set's an element's title attribute using it's current text
  elem.attr("title", elem.text());

  // Set's an element's text color to red
  elem.css("color", "red");

  // Makes the element fade out
  elem.fadeOut();

cache your selectors in variables :)

Another Example 

 Mostly we prefer doing like this ..

// Dynamically building an unordered list from an array

  var localArr = ["Greg", "Peter", "Kyle", "Danny", "Mark"],
 
  list = $("ul.people");

  $.each(localArr, function(index, value) {

    list.append("<li id=" + index + ">" + value + "</li>");

  });

// Dynamically building an unordered list from an array
  var localArr = ["Greg", "Peter", "Kyle", "Danny", "Mark"],
  list = $("ul.people"),
  dynamicItems = "";

  $.each(localArr, function(index, value) {

    dynamicItems += "<li id=" + index + ">" + value + "</li>";

  });

  list.append(dynamicItems);


 Append only once instead of doing it every time ..:)

Jst try :) 

No comments:

Post a Comment