Professional Documents
Culture Documents
CSS Lec-16 Selecting HTML Elements - Fa1f670
CSS Lec-16 Selecting HTML Elements - Fa1f670
CSS Lecture-16
Topic: Selecting HTML Elements
Forms and the elements they contain can be selected from a document using
standard methods like
getElementById(),
getElementsByName(),
getElementsByTagName()
getElementsByClassName()
1) getElementById():
The getElementById() method returns the element that has the ID attribute
with the specified value.
This method is one of the most common methods in the HTML DOM.
Syntax:
element=document.getElementById(id);
For Example: (getid.html)
<html>
<body>
<p id="p1">Hello World</p>
<input type="button" value="Click" onclick="abc()">
</body>
<script>
function abc(){
var ele=document.getElementById("p1").innerHTML="Info Planet";
}
</script>
</html>
Course: Java Script, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Client Side Scripting, Prepared By: Atul Kabra, 9422279260
2) getElementsByTagName():
This method returns a collection(array) of all elements in the document
with the specified tag name.
Note: The parameter value "*" returns all elements in the document.
Syntax:
elements=document.getElementsByTagName (tag_name);
For Example: (gettagname1.html)
<html>
<body>
<p> This is first paragraph </p>
<p> This is second paragraph </p>
<p> This is third paragraph </p>
<p> This is fourth paragraph </p>
<p> This is fifth paragraph </p>
<input type="button" value="Click" onclick="abc()">
</body>
<script>
function abc(){
var e = document.getElementsByTagName("p");
for(i=0;i<e.length;i++)
e[i].style.color="red";
}
</script>
</html>
Course: Java Script, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Client Side Scripting, Prepared By: Atul Kabra, 9422279260
3) getElementsByName()
This method returns a collection(array) of all elements in the document
with the specified name.
Syntax:
elements=document.getElementsByName (name);
Fox Example: (getname.html)
<html>
<body>
<form>
FirstName:<input type="text" id="t1" name="firstname"><br>
LastName:<input type="text" name="lastname" ><br>
Email:<input type="text" name="email"><br>
<input type="button" value="Click" onclick="abc()">
</form>
<p id="p1"></p>
</body>
<script>
function abc(){
var elements = document.getElementsByName("firstname");
document.getElementById("p1").innerHTML=
elements[0].type+" "+elements[0].name+" "+elements[0].value
;
}
</script>
</html>
Course: Java Script, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260
Course: Client Side Scripting, Prepared By: Atul Kabra, 9422279260
4) getElementsByClassName()
This method returns a collection of all elements in the document with the
specified class name.
Syntax:
elements=document.getElementsByClassName(class_name);
Course: Java Script, Info Planet Programming Classes Prepared By: Atul Kabra, 9422279260