DOM Scripting

  1. Use underscore for variable name and camel case for function:
    var temp_celsius;
    function convertToCelsius(){}
  2. Use var to define a local variable, if not defined with var, the variable will be treated as global.
  3. 3 kinds of objects in javascript: Native; User-defined; Host(browser provided).
  4. Native objects:
    var current_date = new Date();
    current_date.getDate();
    // getHours(); getMonth(); 
  5. Objects that are supplied by the web browser are called host objects. An important object: document.
  6. When you load your document into the browser, the DOM comes to life and the document turns into an object.
  7. window object is a global object, and document is a property of window object(window.document).
  8. If the document is a tree(node tree), then the <html> element will be the root.
  9. wildcard: alert(getElementsByTagName("*").length); // will give you the total number of element nodes in a document.
  10. getElementById("purchases").getElementsByTagName("*");
  11. getElementsByClassName(class): will return an array, the order of the class name doesn't matter, matches if the element has addtional classes.
  12. scripters' getElementByClassName function:(work only for single class)
     1 function getElementsByClassName(node, classname){
     2     if(node.getElementsByClassName){
     3         // use the existing method
     4         return node.getElementByClassName(classname);
     5     } else {
     6         var res = new Array();
     7         var elems = node.getElementsByTagName("*");
     8         for(var i = 0; i < elems.length; i++){
     9             if(elems[i].className.indexOf(classname) != -1){
    10                 res[res[i]] = elems[i];
    11             }
    12         }
    13         return res;
    14     }
    15 }
  13. every element node in a document is an object.
  14. getAttribute("title") will return null if there is no such attribute.
  15. if(something) is a shorthand way of if(something != null)
  16. childNodes: it returns an array containing all the children of an element node(with attribute nodes, text nodes as well).
  17. nodeType:(node.nodeType)
    • Element nodes have nodeType value of 1;
    • Attribute nodes have nodeType value of 2;
    • Text nodes have nodeType value of 3.
  18. nodeValue(can be used to retrieve or set value): 
    var description = document.getElementById("description");
    // <p id="description">Choose an image</p>
    var text = description.childNodes[0].nodeValue;  // get the text node value
    // the paragraph's nodeValue itself is empty.
  19. firstChild, lastChild:
    // node.firstChild is equivalent to node.childNodes[0]
    // node.lastChild = node.childNodes[node.childNodes.length - 1]
  20. A simple popup window:
    // syntax:
    window.open(url, name, features);
    // such as:
    function popUp(Url){
        window.open(Url, "popUp", "width=320,height=480");
    }
  21. <a href="#">Bla bla bla</a>: The '#' symbol is used for internal links within document.(in this case, it's an internal link to nowhere)
  22. 'this' can be used to refer to the current element:
    <a href="http://www.google.com" onclick="popUp(this.href);return false;"></a>  // an example of graceful degradation
  23. .href property: 
    // <a id="link" href="http://www.google.com"></a>
    document.write(document.getElementById("link").href);
    // syntax: elementObject.href
  24. the document object is a property of the window object
    window.onload = preparelins;
    function preparelinks(){
    var
    links = document.getElementsByTagName("a"); for(var i = 0; i < links.length; i++){ if(links[i].getAttribute("class") == "popup"){ links[i].onclick = function(){ popUp(this.getAttribute("href")); return false; } } }
    }
    function popUp(Url){window.open(Url, "popup", "width=320,height=480;")}
  25. Object detection:
    function myFunc(){
        if(document.getElementById){
            // statements;
        }
    }
  26. Better test for getElementById:
    if(!getElementById){
        return false;
    }
    // equals:
    if(!getElementById)return false;
  27. Wrap everthing up:
    window.onload = function(){
      if(!document.getElementsByTagName) return false;
         var links = document.getElementsByTagName("a");
         for(var i = 0; i < links.length; i++){
           if(links[i].getAttribute("class") == "popup"){
             link[i].onclick = function(){
               popUp(this.getAttribute("a"));
               return false;
             }
           }
         }
    }
  28. Performance considerations:
    • Minimizing DOM access and markup
    • Assembling and placing scripts
    • Minification(Minification refers to the process of taking your script and “compressing” it by removing the unnecessary bits such as whitespace and comments); better keep two files at hand, one for working, another for minimized file(use min in your file name)
  29. Available minification tools:
    1 Douglas Crockford’s JSMin (http://www.crockford.com/javascript/jsmin.html)
    2 Yahoo!’s YUI Compressor (http://developer.yahoo.com/yui/compressor/)
    3 Google’s Closure Compiler (http://closure-compiler.appspot.com/home)
  30. createElement:
    window.onload = function(){
        var testdiv = document.getElementById("testdiv"),
            para = document.createElement("p"),
            info = "nodeName: ";
        info += para.nodeName;
        info += " nodeType: ";
        info += para.nodeType;
        alert(info);
    }// whenever you create an element, it's called a document fragment. It has nodeName, nodeType value.
  31. appendChild:
    testdiv.appendChild(para);

    Adds a node to the end of the list of children of a specified parent node. If the node already exists it is removed from current parent node, then added to new parent node.

  32. insertBefore: syntax, parentElement.insertBefore(newElement, targetElement);
    var gallery = document.getElementById("imagegallery");
    gallery.parentNode.insertBefore(placeholder, gallery);

    DOM does not have a insert-after method, we can create one:

    function insertAfter(newElement, targetElement){
      var parent = targetElement.parentNode;
      if(targetElement == parent.lastChild){
        parent.appendChild(newElement);
      } else {
        parent.insertBefore(newElement, targetElement.nextSibling);
      }
    }
  33. addLoadEvent function:
    function addLoadEvent(func){
      var oldonload = window.onload;
      if(typeof window.onload != 'function'){
        windwo.onload = func;
      } else {
        window.onload = function(){
          oldonload();
          func();
        }
      }
    }
  34. DOM-core and HTML-DOM:
    // DOM-core:
    document.getElementsByTagName("body")[0];
    // HTML-DOM:
    document.body;
  35. Internet Explorer will count up the child nodes for each <abbr> element and incorrectly come up with zero each time. So, for compatibility issues, you wanna add these lines to deal with <abbr> elements:
    var abbreviations = document.getElementsByTagName("abbr");
    // inside for loop:
    if(abbreviations[i].childNodes.length<1) continue;
  36. Notice:
    <blockquote>
      <p>
        Some sentences...
      </p>
    </blockquote>

    between the end of </p> element and the </blockquote> element, there is a line break, some browers will treat this line break as a text node. That means the lastChild property of blockquote element node isn't p element node, it's a text node. When in doubt, you can use nodeType to check it out.

  37. wildcard character:
    var quoteElements = document.getElementsByTagName("*");
    // returns an array of elements regardless of name
  38. Access key: The accesskey attribute associates an element, such as a link, with a specific key on a keyboard. On many Windows browsers, you can press Alt+access key; on many Mac browsers, you can press Ctrl+access key. 
    <a href="index.html" accesskey="1">Home</a>  // see http://clagnut.com/blog/193/
    // var links = document.getElementsByTagName("a"); links[0].firstChild.nodeValue; // 'Home'// links[0].firstChild.nodeValue; // 'Home'
  39. every element object has a style property, and it is returned as an object. Style information is stored as properties of this style object:
    element.style.property

    when retrieve font-family info, you should:

    element.style.fontFamily; // not element.style.font-family
    // it will treat - as substraction

     The camel-casing convention applies to just about any CSS property that contains one or more dashes. Such as, background-color:backgroundColor; font-weight: fontWeight; magrin-top-marginTopWidth; The style object only work for inline style, not for external or <style> block in the <head> section.

  40. The value of a style property is always a string:
    var para = document.getElementById("example");
    para.style.color = black;     // wrong
    para.style.color = "black";   // right
  41. Using tables for layout is not a good idea,  But you should definitely use tables to display tabular data.
  42. className: an earily version to get access to class attribute:
    element.className = value; // to avoid overwriting the existed class value, you can use:
    element.className += value;
  43. The process of take something very specific and turning it into something more general is called abstraction. Usually for code reuse.
  44. setTimeout: takes 2 arguments, first one is the function name, second is the millisecond before executing the function:
    variable = setTimeout("function", interval);
    clearTimeout(variable); // cancel a pending action
    var num = parseInt(string); // extract number from a string
    var steps = parseInt("39 stepts"); // return 39
    var num2 = parseFloat(string); 
  45. Modernizr: a small library for HTML5 feature detection. Download it(http://www.modernizr.com) and add a script to the <head> of your document:
    <script src="modernizr-1.5.min.js"></script>
  46. To reduce the number of requests, put all your code into a global.js file. Also, use basic.css and do:
    @import url(color.css);
    @import url(layout.css);
    // ...
  47. Several usefull functions:
    function addLoadEvent(func){
        var oldonload = window.onload;
        if(typeof window.onload != 'function'){
            window.onload = func;
        } else {
            window.onload = function(){
                oldonload();
                func();
            }
        }
    } 
    
    function addClass(element, value){
        if(!element.className){
            element.className = value;
        } else {
            newClassName = element.className;
            newClassName += " ";
            newClassName += value;
            element.className = newClassName;   
        }
    }
  48. You can get the URL of the current page using window.location.href;
  49. what labels used for:
    // in case there is no browser support for label focus
    function focusLabels(){
        if(!document.getElementsByTagName) return false;
        var labels = document.getElementsByTagName("label");
        for (var i = 0; i < labels.length; i++){
            if(!labels[i].getAttribute("for")) continue;
            labels[i].onclick = function(){
                var id = this.getAttribute("for");
                if(!document.getElementById(id)) return false;
                var element = document.getElementById(id);
                element.focus();
            }
        }
    }
  50. form.elements.length: returns the number of elements contained by a form, The elements.length property of a Form object returns only those elements that are form elements, such as input elements, textarea elements, and so on. 
  51. form.elements is an array contains all the form elements.
  52. hasChildNodes() method: returns a Boolean value indicating whether the current Node has child nodes or not.
  53. elementNode.removeChild(node): remove a child node;
  54. The encodeURIcomponent() function encodes a URI component:
    var uri="http://w3schools.com/my test.asp?name=ståle&car=saab";
    document.write(encodeURIComponent(uri));
  55. Google's Closure Compiler for minification:http://closure-compiler.appspot.com/home
  56. CDN: Content Delivery Network solves the problems of shared library distribution. Include the URL in the <script> src attribute.
  57. n
  58. n
  59. n
原文地址:https://www.cnblogs.com/wade-case/p/3163394.html