[Source Code] Using JavaScript to manipulate DOM

An Introduction to the Document Object Model
The DOM is a standard way of representing XML documents (instituted by the W3C). It is
not necessarily the fastest, lightest, or easiest to use, but it is the most ubiquitous, with an
implementation existing in most web development programming languages (such as Java,
Perl, PHP, Ruby, Python, and JavaScript). The DOM was constructed to provide an intuitive
way for developers to navigate an XML hierarchy. Even if you’re not completely familiar with
XML, you will get great satisfaction knowing that all HTML documents (which are, in the
eyes of the browser, XML documents) have a DOM representation that is ready to use. 

Pro JavaScript™ Techniques, Apress
Copyright © 2006 by John Resig

 

 <html id="html">
<head id="head">
<title id="title">Introduction to the DOM</title>

<script id="script">

function displayNode( elem ){
//get all text in an elem
elem.innerText;

//get text of a node
elem.nodeValue;

//get HTML in an elem
elem.innerHTML;
}

function test(){
//alert("worked");
//alert(document.documentElement.name);
//var ret = last(document.documentElement);
var ret = "sss"//tag("input")[0];
//alert(ret.constructor== String );

append( tag("ol")[0], "<li>Mouse trap.</li>" );


var li = document.getElementsByTagName("li");
for ( var j = 0; j < li.length; j++ ) {
li[j].style.border = "1px dotted #000";
}

//document.getElementById("everywhere").style.fontWeight = 'bold';
//var ret2 = document.getElementById("head");
//alert(ret2.id);
}

//Finding the Previous Sibling Element in Relation to an Element
function prev( elem ) {
do {
elem = elem.previousSibling;
} while ( elem && elem.nodeType != 1 );
return elem;
}

//Finding the Next Sibling Element in Relation to an Element
function next( elem ) {
do {
elem = elem.nextSibling;
} while ( elem && elem.nodeType != 1 );
return elem;
}

//Finding the First Child Element of an Element
function first( elem ) {
elem = elem.firstChild;
return elem && elem.nodeType != 1 ?
next ( elem ) : elem;
}

//Finding the Last Child Element of an Element
function last( elem ) {
elem = elem.lastChild;
return elem && elem.nodeType != 1 ?
prev ( elem ) : elem;
}

//Finding the Parent of an Element
// parent(elem, 2) == parent( parent(elem) )
function parent( elem, num ) {
num = num || 1;
for ( var i = 0; i < num; i++ )
if ( elem != null ) elem = elem.parentNode;
return elem;
}

//Locating Elements by Id Within an HTML DOM Document
function id(name) {
return document.getElementById(name);
}

//Locating Elements by Tag Name Within an HTML DOM Document
function tag(name, elem) {
// If the context element is not provided, search the whole document
return (elem || document).getElementsByTagName(name);
}

//Searches for All Elements That Have a Particular Class Name
function hasClass(name,type) {
var r = [];
// Locate the class name (allows for multiple class names)
var re = new RegExp("(^|//s)" + name + "(//s|$)");
alert(re);
// Limit search by type, or look through all elements
var e = document.getElementsByTagName(type || "*");
alert("eeee-->"+e.length);
for ( var j = 0; j < e.length; j++ )
// If the element has the class, add it for return
if ( re.test(e[j].className) ) r.push( e[j] );

// Return the list of matched elements
return r;
}

//A Generic Function for Retreiving the Text Contents of an Element
//including all contents of its children Elements
function text(e) {
var t = "";
// If an element was passed, get its children,
// otherwise assume it's an array
e = e.childNodes || e;
// Look through all child nodes
for ( var j = 0; j < e.length; j++ ) {
// If it's not an element, append its text value
// Otherwise, recurse through all the element's children
t += e[j].nodeType != 1 ?
e[j].nodeValue : text(e[j].childNodes);
}
// Return the matched text
return t;
}

//Determining Whether an Element Has a Certain Attribute
function hasAttribute( elem, name ) {
return elem.getAttribute(name) != null;
}

/*
Getting and Setting the Values of Element Attributes

Calling the function with two parameters, for example attr(element, id), returns
that value of that attribute. Calling the function with three parameters, such as attr(element,
class, test), will set the value of the attribute and return its new value. 


Usage Examples:
// Set the class for the first <h1> Element
attr( tag("h1")[0], "class", "header" );
// Set the value for each <input> element
var input = tag("input");
for ( var i = 0; i < input.length; i++ ) {
attr( input[i], "value", "" );
}
// Add a border to the <input> Element that has a name of 'invalid'
var input = tag("input");
for ( var i = 0; i < input.length; i++ ) {
if ( attr( input[i], "name" ) == 'invalid' ) {
input[i].style.border = "2px solid red";
}
}
*/
function attr(elem, name, value) {
// Make sure that a valid name was provided
if ( !name || name.constructor != String ) return '';
// Figure out if the name is one of the weird naming cases
name = { 'for': 'htmlFor', 'class': 'className' }[name] || name;
// If the user is setting a value, also
if ( typeof value != 'undefined' ) {
// Set the quick way first
elem[name] = value;
// If we can, use setAttribute
if ( elem.setAttribute )
elem.setAttribute(name,value);
}
// Return the value of the attribute
return elem[name] || elem.getAttribute(name) || '';
}

/*
The following are functions to manipulate DOM object
including create/insert/delete nodes

Usage:
1. Basic append
// Create a new <li> element
var li = create("li");
attr( li, "class", "new" );
// Create some new text contents and add it to the <li>
append( li, "Thanks for visiting!" );
// Add the <li> onto the top of the first Ordered List
if( first(tag("ol")[0]) == null ){
 //elem 'ol' has no child
 append( tag("ol")[0], li);
}else{
 before( first( tag("ol")[0] ), li );
}

2. Enhance Version of append and insert
append( tag("ol")[0], "<li>Mouse trap.</li>" );

*/

/*
A Generic Function for Creating a New DOM Element

Usage:
var div = create("div");
div.className = "items";
div.id = "all";
*/
function create( elem ) {
return document.createElementNS ?
document.createElementNS( 'http://www.w3.org/1999/xhtml', elem ) :
document.createElement( elem );
}

/*
Basic Version for Inserting and Appending into the DOM

function before( parent, before, elem ) {
// Check to see if no parent node was provided
if ( elem == null ) {
elem = before;
before = parent;
parent = before.parentNode;
}
parent.insertBefore( checkElem( elem ), before );
}

function append( parent, elem ) {
parent.appendChild( checkElem( elem ) );
}

function checkElem( elem ) {
// If only a string was provided, convert it into a Text Node
return elem && elem.constructor == String ?
document.createTextNode( elem ) : elem;
}
*/
//Enhanced Functions for Inserting and Appending into the DOM
function before( parent, before, elem ) {
// Check to see if no parent node was provided
if ( elem == null ) {
elem = before;
before = parent;
parent = before.parentNode;
}
// Get the new array of elements
var elems = checkElem( elem );
// Move through the array backwards,
// because we're prepending elements
for ( var i = elems.length - 1; i >= 0; i-- ) {
parent.insertBefore( elems[i], before );
}
}

function append( parent, elem ) {
// Get the array of elements
var elems = checkElem( elem );
// Append them all to the element
for ( var i = 0; i < elems.length; i++ ) {
parent.appendChild( elems[i] );
}
}

//Converting an Array of Mixed DOM Node/HTML String Arguments into a
//Pure Array of DOM Nodes
function checkElem(a) {
var r = [];
// Force the argument into an array, if it isn't already
if ( a.constructor != Array ) a = [ a ];
for ( var i = 0; i < a.length; i++ ) {
// If there's a String
if ( a[i].constructor == String ) {
// Create a temporary element to house the HTML
var div = document.createElement("div");
// Inject the HTML, to convert it into a DOM structure
div.innerHTML = a[i];
// Extract the DOM structure back out of the temp DIV
for ( var j = 0; j < div.childNodes.length; j++ )
r[r.length] = div.childNodes[j];
} else if ( a[i].length ) { // If it's an array
// Assume that it's an array of DOM Nodes
for ( var j = 0; j < a[i].length; j++ )
r[r.length] = a[i][j];
} else { // Otherwise, assume it's a DOM Node
r[r.length] = a[i];
}
}
return r;
}


/* Remove node
Usage:
// Remove the last <li> from an <ol>
remove( last( tag("ol")[0] ) )
// The above will convert this:
<ol>
<li>Learn Javascript.</li>
<li>???</li>
<li>Profit!</li>
</ol>
// Into this:
<ol>
<li>Learn Javascript.</li>
<li>???</li>
</ol>
// If we were to run the empty() function instead of remove()
empty( last( tag("ol")[0] ) )
// It would simply empty out our <ol>, leaving:
<ol></ol>
*/
// Remove a single Node from the DOM
function remove( elem ) {
if ( elem ) elem.parentNode.removeChild( elem );
}

// Remove all of an Element's children from the DOM
function empty( elem ) {
while ( elem.firstChild )
remove( elem.firstChild );
}

//--></script>

</head>
<body id="body">
<h1 id="h1">Introduction to the DOM</h1>
<p id="p" class="test">There are a number of reasons why the
DOM is awesome, here are some:</p>
<ul id="ul">
<li id="everywhere">It can be found everywhere.</li>
<li class="test" id="li2">It's easy to use.</li>
<li class="test" id="li3">It can help you to find what you want, really quickly.</li>
</ul>
<ol>

</ol>

<input id="input1" name="Submit" type="submit"  style = " width : 100  "class="" value="Test" οnclick="test();">
</body>
</html>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值