Wednesday, March 25, 2015

DOM Manipulation with js

1. window object -> as global object

2. DOM nodes: Element, Text, Document

Element: like <p> etc.
Text: represents all text(within elements) within a page.
Document: represents the entire document. root-node of the DOM hierarchy.

3. script element

<script type="text/javascript">
</script>

Linked to external scripts:
<script type="text/javascript" src="example.js"></script>

4. Accessing DOM nodes:

var test1 = document.getElementById('id-name');

var test2 = document.getElementsByTagName('ul'); -->return a live node collection/list

//Access single unordered list: [0] index
var unorderedList = document.getElementsByTagName('ul')[0];

//create Node list of all list items within the UL
var allListItems = unorderedList.getElementsByTagName('li');

for(var i=0, length = allListItems.length; i<length; i++){
         alert(allListItems[i].firstChild.data);
}

5. Traversing the DOM
Node.childNodes: access all direct child nodes of a single element.
Node.firstChild -> first item in the 'childNodes' array
Node.lastChild -> last item(last child node, can be aan element node ,a text node or a comment node)
Node.parentNode: access to the parent node of your current node. [There is only one parent node. In order to get grandparent: Node.parentNode.parentNode]
Node.nextSibling: access to the next node on the same level within the DOM tree
Node.previousSibling: access to the previous node on the same level.

Traversing the DOM
Note: the list items can only be retrieved in that fashion if there is no white-space between them. The space between the <ul> and the first <li> counts as a node itself.
Thus, when loop through the 'childNodes' array, you can test the 'nodeType'.
[use: node.nodeType]
nodeType == 1 ---> It's an element
nodeType == 2 ---> It's an attribute
nodeType == 3 ---> It's a text node.

6. Manipulating Elements
change the color: document.getElementById('id-name').style.color = "#FF0000";
change paddings: document.getElementById('id-name').style.padding = '2px 3px 0 3px';
change margin-top: document.getElementById('id-name').style.marginTop = '20px';
change the content within element: document.getElementById('id-name').innerHTML = "new test";

[ElementNode VS TextNode]

example1:
var myIntro  = document.getElementById('intro'); //suppose 'intro' is the id of <p>
var someText = 'This is the text that needs to be added';
var textNode  = document.createTextNode(someText);
myIntro.appendChild(textNode);//add text node to the paragraph

example2:
var myIntro = document.getElementById('intro');
var myNewLink = document.createElement('a');
myNewLink.href = 'http://google.com';
myNewLink.appendChild(document.createTextNode('Visit Google'));
myIntro.appendChild(myNewLink); //append it to the paragraph

example3:
insertBefore() method inserts a node as a child, right before an existing child, which you specify.

function insertAfter(target, bullet){
target.nextSibling ? target.parentNode.insertBefore(bullet, target.nextSibling) : target.parentNode.appendChild(bullet);
}

example4:
var element = document.createElement(tagName);

[Getting and Setting the Class Name]
var cName = element.className; //get the class name of "element"
otherElement.className = cName; //set the class name of "otherElement"

[Getting and Setting the ID]
var idStr = element.id; //get the id of "element"
otherElement.id = idStr; // set the "otherElement"'s id

[Accessing elements by Class Names]
elements = document.getElementsByClassName(names);//not supported from IE8

[Accessing first found Selector]
Return the first element within the document (using depth-first pre-order traversal of the document's nodes) that matches the specified group of selectors.
element = document.querySelector('selector1, selector2,...');
example:
element = document.querySelector('div#container'); //返回id为container的首个div
element = document.querySelector('.foo, .bar'); //返回带有foo或者bar样式类的首个元素

[Accessing an Array of Selectors]
Return a list of the elements within the document that match the specified group of selectors.
elementList = document.querySelectorAll(selectors);
example:
elements = document.querySelectorAll('div.foo'); //返回所有带有foo样式类的div

[Children of a given element]
var ndList = element.childNodes;

[Next Sibling of a given element]
nextNode = node.nextSibling; //returns the node immediately following the specified one in its parent's childNodes list, or null if the specified node is the last node in that list. 同级别,有共同的父亲节点

[Child Elements of a given object] -->read only
the items in the returned collection are objects and not strings. To get data from those node objects, you must use their properties(e.g. element.children[1].nodeName)
var elList = element.children;

[Next element Sibling]
var nextElem = element.nextElementSibling;

****nextSibling VS nextElementSibling****
nextElementSibling always returns an element
nextSibling can return any kind of node
e.g.
<p><span id="span-01">Here is span-01</span>
Some text at the top level
<span id="span-02">Here is span-02</span></p>

document.getElementById('span-01').nextElementSibling is "span-02"
document.getElementById('span-02').nextSibling is the text node containing "some text at the top level"

[removeChild]
every node has a method removeChild that takes as an argument the node that is to be destroyed. This node needs to be called on the node's parent.

7. Events
Browser events are part of the DOM API (not part of js)
Mouse Events:
mousedown, mouseup, click, dbclick, mouseover, mouseout, mousemove
Key Events:
keypress, keydown, keyup
Form Events:
select, change, submit, reset, focus, blur
Others:
load (-->fired when finished loading all content within a document), resize, scroll, unload (-->fired when the user agent removes all content from a window or a frame, e.g when you leave a page)

8. Event handling
//Format: target.addEventListener(type, function, useCapture); useCapture is a boolean value that specifies whether the event should be executed in the capturing or in the bubbling phase.
function introClick(){
console.log("hello, world");
}

[for W3C model]
var myIntro = document.getElementById('Intro');
myIntro.addEvenetListener('click', introClick, false);

[for IE]
var myIntro = document.getElementById('Intro');
myIntro.attachEvent('onClick', introClick);

[cross-browser] - add event listener
function addEvent(elem, type, fn) {
if(elem.attachEvent){
elem.attachEvent('on'+type, fn);
return
}
if(elem.addEventListener){
elm.addEventListner(type, fn, false);
}
}

[cross-browser] - remove event listener
function removeEvent(elem, type, fn){
if(elem.detachEvent){
elem.detachEvent('on'+type, fn);
}
if(elem.removeEventListener){
elem.remvoeEventListener(type, fn, false);
}
}

//If you want an action to occur on an event only the first time it's clicked
var myIntro = document.getElementById('Intro');
addEvent(myIntro, 'click', oneClickOnly);
function oneClickOnly(){
console.log("one time");
removeEvent(myIntro, 'click', oneClickOnly);
}

//for anonymous function:
addEvent(myIntro, 'click', function(){
console.log("one time");
removeEvent(myIntro, 'click', arguments.callee);
})

9. The Event Object
function myEventHandler(e){
e = e || window.event;

//Preventing the default action of an event:
if(e.preventDefault){
 e.preventDefault();
}else{
e.returnValue = false; //For IE
}

}

10. Event bubbling - "aka event propagation"
The event fires on the target element. The event then fires on each and every ancestor of that element - the event bubbles up through the DOM until it reaches the top-most element:
The bubbling behavior can be stopped at ANY time during the process. For example, if you only want the event to bubble up to the paragraph but no further(not to the body node) you can use "stopPropagation":
function myParagraphEventHandler(e){
e = e || window.event;
if(e.stopPropagation){
e.stopPropagation(); //W3C compliant browsers
} else{
e.cancelBubble  = true; //IE
}
}

11. Event delegation
It describes the process of applying an event handler to a container element and then using that as the basis for all child elements.

var myTable = document.getElementById('my-table');
myTable.onclick = function(){
e = e || window.event;
var targetNode = e.target || e.srcElement;

if(targetNode.nodeName.toLowerCase() === 'tr'){
alert('You clicked a table row!');
}
}



Exercise:
  1. Add an event handler to each star (or to the table) so that when a star is clicked it toggles between on and off.
  2. Send the clicked star's number (0-99) and new state (0 or 1) to the server in this format: /collab.py?n=99&s=1
  3. The resulting response is a 100 character string that should be used to turn on or off each of the 100 stars.
<table id="star_table">
  <tr>
    <td><img id="star_0" src="star_off.gif"><td>
    <td><img id="star_1" src="star_off.gif"><td>
    <td><img id="star_2" src="star_off.gif"><td>
    ...
  <tr>
  </tr>
    <td><img id="star_10" src="star_off.gif"><td>
    <td><img id="star_11" src="star_off.gif"><td>
    <td><img id="star_12" src="star_off.gif"><td>
    ...
  <tr>
  ...
</table>

var table = document.getElementById('star_table');
var stars = table.getElementsByTagName('img');

var getStars = function(){
return document.getElementById('star_table').getElementsByTagName('img');
}

var updateStars = function(){
var stars = getStars();
if(this.readyState == 4 && this.status==200){
for(var i=0; i<this.responseText.length;i++){
stars[i].src == this.responseText.charAt(i) == '0' ? 'star_off.gif':'star_on.gif';
}
}
}

var computeStarIndex = function(stars, star){
for(var i=0; i<stars.length; i++){
if(stars[i]==star){
return i;
}
}
return -1;
};

var requestUpdate = function(params){
var req = new XMLHttpRequest();
req.open('POST', '/collab.py', true);
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
req.onreadystatechange = updateStars;
req.send(params);
}

var sendRequest = function(starIndex, newState){
var params = 'n='+ starIndex + '&s=' + newState;
requestUpdate(params);
};

var clickStar = function(e){
if(e.target.src){
var stars = getStars();
var starIndex = computeStarIndex(stars, e.target);
var newState = e.target.src.endsWith('star_off.gif')?1:0;
sendRequest(starIndex, newState);
}
};

table.addEventListener('click', clickStar, false);
var intervalld = window.setInterval(requestUpdate,500);

12. DOM tables
  • table
    • caption
      • childNodes[]
    • tHead
      • rows[]
        • cells[]
          • childNodes[]
    • tFoot
      • rows[]
        • cells[]
          • childNodes[]
    • tBodies[]
      • rows[]
        • cells[]
          • childNodes[]
caption
References the caption of the table
thead
References the thead of the table, if there is one
tfoot
References the tfoot of the table, if there is one
tbodies
A collection with one entry for each tbody (usually just table.tbodies[0])
Each thead, tbody and tfoot has a rows collection with an entry for each row in that thead, tbody or tfoot. Each row has a cells collection containing every td or th cell in that row. Each cell then contains the usual DOM references to its contents.

Methods: createTHead(), createTFoot(), deleteTHead(), deleteTFoot(), createCaption(), deleteCaption()

[Adding a row to a table]
var theTable = document.getElementById('tableId');
theTable.tBodies[0].appendChild(document.createElement('tr')); //The tBodies collection returns a collection of all <tbody> elements in a table.

[Adding one cell to every row in a table]
var theTable = document.getElementById('tableId');
for(var x=0; x<theTable.tHead.rows.length;x++){
var y = document.createElement('td');
y.appendChild(document.createTextNode('Thead cell text'));
theTable.tHead.rows[i].appendChild(y);
}

for(var y=0; y<theTable.bodies.length;y++){
for(var x=0; x<theTable.bodies[y].rows.length;x++){
var z = document.createElement('td');
z.appendChild(document.createTextNode('Tbody cell text'));
theTable.tbodeis[y].rows[x].appendChild(z);
}
}

13. DOM CSS
[the class attribute of the element removal, change]
element.className="";
element.className=''newClassName'';

[getComputedStyle, currentStyle]
The currentStyle property (IE) and getComputedStyle (standard) method allow to get the live value of the style property, after all styles are applied.

var oElement = document.getElementById('mydiv');
var oColor;
if(window.getComputedStyle){
oColor = window.getComputedStyle(oElement, null).color;
}else if(oElement.currentStyle){
oColor = oElement.currentStyle.color;
}

14. DOM style sheets
All stylesheets are available through the document.styleSheets collection. This includes stlesheets added using <style> and <link> tags, including persistent, preferred and alternate stylesheets, no matter if they are enabled or not.

If you hava a reference to the LINK or STYLE element, you can reference the associated stylesheet object using the sheet property of the element.
var theSheet = document.getElementsByTagName('style')[0].sheet;

Similarly, if you have a reference to the StyleSheet object, you can reference the associated LINK or STYLE element by using the ownerNode property of the StyleSheet object.
var theElement = document.styleSheets[0].ownerNode;

15. stopPropagation

<script>
function doSomething (obj,evt) {
 alert(obj.id);
 var e=(evt)?evt:window.event;
 if (window.event) {
  e.cancelBubble=true;// ie下阻止冒泡
 } else {
  //e.preventDefault();
  e.stopPropagation();// 其它浏览器下阻止冒泡
 }
}
</script>

<body>
<div id="parent1" onclick="alert(this.id)" style="width:250px;background-color:yellow">
 <p>This is parent1 div.</p>
 <div id="child1" onclick="alert(this.id)" style="width:200px;background-color:orange">
  <p>This is child1.</p>  由于冒泡传递,先弹出child1,接下来会弹出parent1
 </div>

 <p>This is parent1 div.</p>
</div>
<br />
<div id="parent2" onclick="alert(this.id)" style="width:250px;background-color:cyan;">
 <p>This is parent2 div.</p>
 <div id="child2" onclick="doSomething(this,event);" style="width:200px;background-color:lightblue;"> 使用stopPropagation()函数阻止了冒泡传递,因此只弹出child1
  <p>This is child2. Will bubble.</p>
 </div>
 <p>This is parent2 div.</p>
</div>
</body>

16. implement getElementsByAttribute
function getElementByAttribute(attribute){
var allElements = document.getElementsByTagName('*'),
      elem,
      found = [];
for(var i=0; i<allElements.length;i++){
elem = allElements[i];
if(elm.getAttribute(attribute)){
found.push(elem);
}
}
return found;
}

check the attribute while getting the elements
function getElementsByAttribute2(attr){
var found = [],
      child;

function getNodeText(node){
if(node && node.childNodes && node.childNodes.length){
for(var i=0, len=node.childNodes.length;i<len;i++){
     child = node.childNodes[i];
     if(child && child.getAttribute && child.getAttribute(attr)){
           found.push(child);
     }
     getNodeText(child);
}
}
}
else{
  if(node.getAttribute && node.getAttribute(attr)){
   found.push(node);
}
}
}

17. add Class
function addClass(selector, className){
var elem  = document.querySelector(selector);
if (elem){
elem.classList.add(className);
}
}
//remove a class: elem.classList.remove(className);
//toggling a class: elem.classList.toggle(className);
//check whether class exists: elem.classList.contains(className);

18. check descendant
function isDescendant(parent, child){
while(child.parentNode){
if(child.parentNode == parent) return true;
else
 child = child.parentNode;
}
return false;
}

19. innerHTML vs appendChild
var el = document.getElementById('myList');
el.innerHTML =  '<li>a</li>';
--------------------------------------
var li = document.createElement("li");
var text = document.createTextNode("Only one item");
li.appendChild(text);
el.appendChild(li);

20. DOM ready
option1: put the script in the last tag of html body element. DOM would be ready by the time browser hits the script tag.

option2: Place your code inside a DOMContentLoaded handler. This event will be fired when DOM is completed loaded.
document.addEventListener('DOMContentLoaded', function(){
//put script here
});

option3: Watch changes in the readyState of the document.
document.onreadystatechange = function(){
if(document.readyState == "complete"){
//put script here
}
}

21. Event Delegate
<ul id="listToDestroy"> <li><a href="#">first item</a></li> <li><a href="#">second item</a></li> <li><a href="#">third item</a></li> <li><a href="#">forth item</a></li> <li><a href="#">Fifth item</a></li> </ul>
document.getElementById("listToDestroy").addEventListener('click', function(e){
var elm = e.target.parentNode;-->li
elm.parentNode.removeChild(elm); -->delete current li
e.preventDefault();
})

22. Destroy Button
document.getElementById("doubleHolder").addEventListener('click', function(e){
if(e.target.classList.contains('double')){
var btn = document.createElement('button');
btn.setAttributue('class', 'double');
btn.innerHTML = 'double';

var btn2 = document.createElement('button');
btn2.setAttributue('class', 'double');
btn2.innerHTML = 'double';

this.appendChild(btn);
this.appendChild(btn2);
this.removeChild(e.target);
}
});

23. Capture all clicks
document.querySelector('body').addEventListener('click', function(e){
console.log('clicked');
});

or

window.onclick = function(e){
console.log('someone clicked', e.target);
}

//Can use stopPropagation() to stop event bubbling

24. All text in a page
document.body.innerText;

By accessing DOM
function getNodeText(node){
var allText = [];
function getNodeText(node){
if(node && node.childNodes && node.childNodes.length){
for(var i=0; i<node.childNodes.length; i++){
getNodeText(node.childNodes[i]);
}
}
else{
allText.push(node.nodeValue);
}
}
getNodeText(node);
}
return allText.join('');

25. defer vs async [用于加载文件]
(1). HTML parser will ignore defer and async keyword for inline script[script that doesn't have src attribute]
(2).<script src="script.js"></script>
不等待后续载入的dom elements(parser pause parsing)
(3) <script async src="script.js"></script>
加载和渲染后续文档元素的过程将和 script.js 的加载与执行并行进行(异步
(4) <script defer src="script.js"></script>
加载后续文档元素的过程将和 script.js 的加载并行进行(异步),但是 script.js 的执行要在所有元素解析完成之后,DOMContentLoaded 事件触发之前完成。
(script will be executed when DOM is available)

26
How could you run event handler in the capturing phase not in bubble phase?
useCapture = true the Events execute top to down in the capture phase when false it does a bubble bottom to top.
How could you prevent multiple event handler to be fired for an event?
If event listeners are attached for the same type events(click, keydown. etc) of an element, you can call event.stopImmediatePropagation() in the first event handler.

No comments:

Post a Comment