W3C.US

  • Increase font size
  • Default font size
  • Decrease font size
Home Tutorial Javascript Book Javascript & DOM (2)

Javascript & DOM (2)

E-mail Print PDF

There are 3 methods in javascript to get the element(s) in DOM: getElementById(), getElementsByName(), and getElementsByTagName().

If the element has been set a unique element id, we can use getElementById to access it:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>ById</title>
<style type="text/css">
<!--
#docid{
height:400px;
width:400px;
background-color:#999;}
-->
</style>
</head>
<body><div id="docid" name="docname" onClick="bgcolor()"></div>
</body>
</html>
<script language="JavaScript" type="text/JavaScript">
<!--
function bgcolor(){
document.getElementById("docid").style.backgroundColor="#0000AA"
}
-->
</script>

 And also, we can use getElementsByName to access the element:

getElementsByName("docname")

Because the element's name is not unique, so the function return an array, include all element has the same name.

We can use getElementsByName("thename")[0] to access the first element name "thename", [1] the second, and so on.

getElementsByTagName()  is used to fetch the array of all elements has the same tag name.

<!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> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Byname,tag</title> <style type="text/css"> <!-- #docid1,#docid2{ margin:10px; height:400px; width:400px; background-color:#999;} --> </style> </head> <body> <div name="docname" id="docid1" onClick="bgcolor()"></div> <div name="docname" id="docid2" onClick="bgcolor()"></div> </body> </html> <script language="JavaScript" type="text/JavaScript"> <!-- function bgcolor(){ var docnObj=document.getElementsByTagName("div"); docnObj[0].style.backgroundColor = "black"; docnObj[1].style.backgroundColor = "black"; } --> </script>

The red line, fetch all div elements to an array.