Convenient reductions at job with DOM

The spelling monstropodobnykh document.getElementById (), document.createElement () and a method at job with DOM in JavaScript is possible to avoid others, using functions with simple and convenient names.


Situation (meets quite often): it is necessary for you to get in function access to several HTML-elements, having changed their any property, for example style. Access as it is accepted and it is convenient, we receive through the identifier:



function changeStyle () {

      document.getElementById ("firstId") .style.display = "none";

      document.getElementById ("secondId") .style.color = "green";

      document.getElementById ("thirdId") .style.backgroundColor = "*FF0000";

      document.getElementById ("fourthId") .style.fontWeight = "bold";

      document.getElementById ("fifthId") .style.paddinpTop = "10px";

}


In this simple code instead of bulky document.getElementById it is possible to use simple and convenient function gebi (under the first letters get Element By Id). Its  code:



function gebi (id) {

      return document.getElementById (id);

}


Function is engaged completely same, gets access to an element on his  identifier, but has shorter and convenient form of recording:



function changeStyle () {

      gebi ("firstId") .style.display = "none";

      gebi ("secondId") .style.color = "green";

      gebi ("thirdId") .style.backgroundColor = "*FF0000";

      gebi ("fourthId") .style.fontWeight = "bold";

      gebi ("fifthId") .style.paddingTop = "10px";

}


It is possible to beat other methods (and their combinations with properties) for job with DOM, reducing their recording:



// Returns the element created on a transferred{handed} name

function ce (name) {

      return document.createElement (name);

}

// Returns affiliated object style for an element, id which it is passed function

function styleId (id) {

      if (el = document.getElementById (id)) {

            return el.style;

} else return false;

}

// Then change of style properties of the previous example will be written down so:

function changeStyle () {

      styleId ("firstId") .display = "none";

      styleId ("secondId") .color = "green";

      styleId ("thirdId") .backgroundColor = "*FF0000";

      styleId ("fourthId") .fontWeight = "bold";

      styleId ("fifthId") .paddingTop = "10px";

}



Pluss and minuses


[+] the Reduced syntax and more readable code.

[-] It is necessary to declare functions and to remember them during a spelling of a code

From here we judge, that reductions are convenient, when you repeatedly use this or that method. Reduction of productivity thus it is not observed.