A lot of these scripts are copied from DOM Scripting - Web Design with JavaScript and the Document Object Model by Jeremy Keith.
Other examples are taken from JavaScript: The Definitive Guide (5th edition) by David Flanagan. Copyright 2006 O'Reilly Media, Inc., 978-0-596-10199-2.
document.getElementsByTagName() | gets list of a, ul, etc | document.getElementsByTagName("ul") | in this browser |
document.getElementById() | get's particular ID item | document.getElementById("blah") | in this browser |
element.childNodes | get's list of childNodes of element | body_element.childNodes | in this browser |
element.getElementsByTagName() | gets all tags below current element | in this browser | |
getAttribute() | gets the attribute of a particular node |
var AVar = document.getElementsByTagName("div"); var danode = AVar[0]; var txt = danode.getAttribute("id"); | in this browser |
setAttribute()
As it turns out this doesn't work in IE6/MS Windows. For example, for a class, try something like:
element['class'] = element['className'] = "monoborder";
|
sets the attribute of a particular node |
var bordertochange = document.getElementById("SetAttrTest"); //bordertochange.setAttribute("class","monoborder"); //bordertochange.class = "monoborder"; //bordertochange['class'] = "monoborder"; bordertochange['className'] = "monoborder"; | |
removeAttributes() |
function getSelectedText() { if (window.getSelection) { // This technique is the most likely to be standardized. // getSelection() returns a Selection object, which we do not document. return window.getSelection().toString(); } else if (document.getSelection) { // This is an older, simpler technique that returns a string return document.getSelection(); } else if (document.selection) { // This is the IE-specific technique. // We do not document the IE selection property or TextRange objects. return document.selection.createRange().text; } } function prouttext() { var prouttextid = document.getElementById("prouttext"); var selectedtext = getSelectedText(); var prouttext = document.createTextNode(selectedtext); var dachildren = prouttextid.childNodes; for (var i=0; i<dachildren.length; ) prouttextid.removeChild(dachildren[i]); prouttextid.appendChild(prouttext); } <form><input type=button value="what is selected text" onclick="prouttext();"></form> <div id="prouttext"></div>Select some text and press the button below...
Node | Document | HTMLDocument | |
CharacterData | Text | ||
Comment | |||
Attr | |||
Element | HTMLElement | HTMLHeadElement | |
HTMLBodyElement | |||
HTMLTitleElement | |||
HTMLParagraphElement | |||
HTMLInputElement | |||
HTMLTableElement | |||
etc... |
Document.createElement() | |
Document.createTextNode() | Create a new Text node |
Document.creteDocumentFragment() | Create doc fragment that you can put children into. When using any the Node methods like .appendChild(), replaceChild(), or .insertBefore(), you pass the fragment, and all the children are appended, replaced, or inserted. |
Node.appendChild() | adds a node to the doc tree by appending it to the childNodes[] array. If node is already in the doc tree, it is removed and then reinserted at new pos.
Click here to see the function below in action... function addline(daline) { var dv = document.createElement("div") var text = document.createTextNode(daline); dv.appendChild(text); //insert in beginning of doc document.body.insertBefore(dv, document.body.firstChild) } Click here to see a more involved function add a table. |
Node.replaceChild() | replaces the childnode with another |
Node.removeChild() | removes the childnode |
Node.insertBefore() | insert node into doc tee before specified child of this node. If already in tree, it is removed and reinserted at its new location. |
Element.innerHTML | Query or insert HTML text representing the children of the element.
function addinnerhtml() { var dadiv11 = document.getElementById("dadiv"); dadiv11.innerHTML = "hello <b>the</b>re"; } <div id="dadiv"></div> <form><input type=button value="insert innerhtml" onclick="addinnerhtml(); return(false);"></form> |
CharacterData.appendData(), .deleteData(), .insertData(), .replaceData(), substringData() | work with text and comment nodes |
.length | get's length of list | body_element.childNodes.length | |
nodeValue | get/set the value/text of a particular node | see below... | |
nodeType |
number is noteType value
|
function checkdocprops) { var string44 = ""; var props44; for (props44 in document.links.namedlink) string44 += props44 + "-" + document.links.namedlink[props44] + '\n'; alert(string44); return(false); }
//function to display or hide a given element function showHideItems(myItem, myButton){ //this is the ID of the hidden item var myItem = document.getElementById(myItem); //this is the ID of the plus/minus button image var myButton = document.getElementById(myButton); if (myItem.style.display != "none") { //items are currently displayed, so hide them myItem.style.display = "none"; swapImage(myButton,"plus"); } else { //items are currently hidden, so display them myItem.style.display = "block"; swapImage(myButton,"minus"); } } //function to swap an image based on its current state function swapImage(myImage, state) { if (state == "minus") { myImage.src = "images/minus.gif"; } else { myImage.src = "images/plus.gif"; } }
<a onclick="showHideItems('item1', 'button1');" title="Show/hide items"> <img src="images/plus.gif" border="0" id="button1" name="button1" /> <!-- begin div containing hidden items --> <div id="item1" style="display:none"> My hidden content </div>
// @name The Fade Anything Technique // @namespace http://www.axentric.com/aside/fat/ // @version 1.0-RC1 // @author Adam Michela var Fat = { make_hex : function (r,g,b) { r = r.toString(16); if (r.length == 1) r = '0' + r; g = g.toString(16); if (g.length == 1) g = '0' + g; b = b.toString(16); if (b.length == 1) b = '0' + b; return "#" + r + g + b; }, fade_all : function () { var a = document.getElementsByTagName("*"); for (var i = 0; i < a.length; i++) { var o = a[i]; var r = /fade-?(\w{3,6})?/.exec(o.className); if (r) { if (!r[1]) r[1] = ""; if (o.id) Fat.fade_element(o.id,null,null,"#"+r[1]); } } }, fade_element : function (id, fps, duration, from, to) { if (!fps) fps = 30; if (!duration) duration = 3000; if (!from || from=="#") from = "#FFFF33"; if (!to) to = this.get_bgcolor(id); var frames = Math.round(fps * (duration / 1000)); var interval = duration / frames; var delay = interval; var frame = 0; if (from.length < 7) from += from.substr(1,3); if (to.length < 7) to += to.substr(1,3); var rf = parseInt(from.substr(1,2),16); var gf = parseInt(from.substr(3,2),16); var bf = parseInt(from.substr(5,2),16); var rt = parseInt(to.substr(1,2),16); var gt = parseInt(to.substr(3,2),16); var bt = parseInt(to.substr(5,2),16); var r,g,b,h; while (frame < frames) { r = Math.floor(rf * ((frames-frame)/frames) + rt * (frame/frames)); g = Math.floor(gf * ((frames-frame)/frames) + gt * (frame/frames)); b = Math.floor(bf * ((frames-frame)/frames) + bt * (frame/frames)); h = this.make_hex(r,g,b); setTimeout("Fat.set_bgcolor('"+id+"','"+h+"')", delay); frame++; delay = interval * frame; } setTimeout("Fat.set_bgcolor('"+id+"','"+to+"')", delay); }, set_bgcolor : function (id, c) { var o = document.getElementById(id); o.style.backgroundColor = c; }, get_bgcolor : function (id) { var o = document.getElementById(id); while(o) { var c; if (window.getComputedStyle) c = window.getComputedStyle(o,null).getPropertyValue("background-color"); if (o.currentStyle) c = o.currentStyle.backgroundColor; if ((c != "" && c != "transparent") || o.tagName == "BODY") { break; } o = o.parentNode; } if (c == undefined || c == "" || c == "transparent") c = "#FFFFFF"; var rgb = c.match(/rgb\s*\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)/); if (rgb) c = this.make_hex(parseInt(rgb[1]),parseInt(rgb[2]),parseInt(rgb[3])); return c; } } window.onload = function () { Fat.fade_all(); }
shortcut("Ctrl+Shift+X", function() { alert("Hi there!"); });
function shortcut(shortcut,callback,opt) { //Provide a set of default options var default_options = { 'type':'keydown', 'propagate':false, 'target':document } if(!opt) opt = default_options; else { for(var dfo in default_options) { if(typeof opt[dfo] == 'undefined') opt[dfo] = default_options[dfo]; } } var ele = opt.target if(typeof opt.target == 'string') ele = document.getElementById(opt.target); var ths = this; //The function to be called at keypress var func = function(e) { e = e || window.event; //Find Which key is pressed if (e.keyCode) code = e.keyCode; else if (e.which) code = e.which; var character = String.fromCharCode(code).toLowerCase(); var keys = shortcut.toLowerCase().split("+"); //Key Pressed - counts the number of valid keypresses - if it is same as the number of keys, the shortcut function is invoked var kp = 0; //Work around for stupid Shift key bug created by using lowercase - as a result the shift+num combination was broken var shift_nums = { "`":"~", "1":"!", "2":"@", "3":"#", "4":"$", "5":"%", "6":"^", "7":"&", "8":"*", "9":"(", "0":")", "-":"_", "=":"+", ";":":", "'":"\"", ",":"<", ".":">", "/":"?", "\\":"|" } //Special Keys - and their codes var special_keys = { 'esc':27, 'escape':27, 'tab':9, 'space':32, 'return':13, 'enter':13, 'backspace':8, 'scrolllock':145, 'scroll_lock':145, 'scroll':145, 'capslock':20, 'caps_lock':20, 'caps':20, 'numlock':144, 'num_lock':144, 'num':144, 'pause':19, 'break':19, 'insert':45, 'home':36, 'delete':46, 'end':35, 'pageup':33, 'page_up':33, 'pu':33, 'pagedown':34, 'page_down':34, 'pd':34, 'left':37, 'up':38, 'right':39, 'down':40, 'f1':112, 'f2':113, 'f3':114, 'f4':115, 'f5':116, 'f6':117, 'f7':118, 'f8':119, 'f9':120, 'f10':121, 'f11':122, 'f12':123 } for(var i=0; k=keys[i],i1) { //If it is a special key if(special_keys[k] == code) kp++; } else { //The special keys did not match if(character == k) kp++; else { if(shift_nums[character] && e.shiftKey) { //Stupid Shift key bug created by using lowercase character = shift_nums[character]; if(character == k) kp++; } } } } if(kp == keys.length) { callback(e); if(!opt['propagate']) { //Stop the event //e.cancelBubble is supported by IE - this will kill the bubbling process. e.cancelBubble = true; e.returnValue = false; //e.stopPropagation works only in Firefox. if (e.stopPropagation) { e.stopPropagation(); e.preventDefault(); } return false; } } } //Attach the function with the event if(ele.addEventListener) ele.addEventListener(opt['type'], func, false); else if(ele.attachEvent) ele.attachEvent('on'+opt['type'], func); else ele['on'+opt['type']] = func; }