JavaScript中DOM树的Node接口的一些简单应用

1. 用类名查找元素

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN
" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd
">

<html xmlns="http://www.w3.org/1999/xhtml
" >

<head>

    <title>Untitled Page</title>

    <script type="text/javascript
">

    //本页方法:用类名选择元素


        function
 getElements(cla) {

            var
 elements = document
.getElementsByTagName("*
");

            var
 elems = [];

            for
 (var
 i = 0; i < elements.length
; i++) {

                if
 (elements[i].className && has(elements[i].className,cla)) {

                    elems.push(elements[i]);

                }

            }

            return
 elems;

        }

        function
 has(ele, name
) {

            var
 clla = [];

            if
 (ele) clla = ele.split(' ');

            for
 (var
 i = 0; i < clla.length
; i++)

                if
 (clla[i] == name
) {return
 true
 };

            return
 false
;

        }

    </script>

    <style type="text/css
">

    .h

    {background-color:Aqua;

    }

    </style>

</head>

<body>

<i id="iiii
" class
="h
">Just test.</i><br />

<span id="ssss
" class
="h
">hehe</span>

<script type="text/javascript
">

    var
 e = getElements("h
");

    var
 nn = ""

    for
 (var
 i = 0; i < e.length
; i++) {

            nn +="id: 
" + e[i].id + "/n
";

        nn += "------line------/n
";

    }

    alert
(nn);

</script>

</body>

</html>

 




<
script
>

// This function takes a Node n, replaces it in the tree with an Element node
// that represents an HTML <
b
>
 tag, and then makes the original node the
// child of the new <
b
>
 element.
function embolden(n) {
    if (typeof n == "string") n = document.getElementById(n); // Lookup node
    var b = document.createElement("b"); // Create a new <
b
>
 element
    var parent = n.parentNode;           // Get the parent of the node
    parent.replaceChild(b, n);           // Replace the node with the <
b
>
 tag
    b.appendChild(n);                    // Make the node a child of the <
b
>
 element
}
</
script
>


<!-- A couple of sample paragraphs -->

<
p
 id
="p1"
>
This <
i
>
is</
i
>
 paragraph #1.</
p
>

<
p
 id
="p2"
>
This <
i
>
is</
i
>
 paragraph #2.</
p
>

<!-- A button that invokes the embolden() function on the element named p1 -->

<
button
 onclick
="embolden('p1');"
>
Embolden</
button
>


posted @ 2010-05-14 14:23  damoyan  阅读(147)  评论(0编辑  收藏  举报