JavaScript DOM
JavaScript DOM
<p id="demo"></p>
<script>
var x = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML =
'The text in first paragraph (index 0) is: ' + x[0].innerHTML;
</script>
Finding Elements by Class
<p>Hello World!</p>
<p id="demo"></p>
<script>
var x = document.getElementsByClassName("intro");
document.getElementById("demo").innerHTML =
'The first paragraph (index 0) with class="intro": ' + x[0].innerHTML;
</script>
Finding Elements by CSS Selector
<p>Hello World!</p>
<p id="demo"></p>
<script>
var x = document.querySelectorAll("p.intro");
document.getElementById("demo").innerHTML =
'The first paragraph (index 0) with class="intro": ' + x[0].innerHTML;
</script>
Finding Elements by Object Collections
• doument.anchors
• document.body
• document.forms
• document.head
• document.images
• document.links, etc.
Finding Elements by document.forms
<form id="frm1" action="/action_page.php"> <script>
First name: <input type="text" name="fname" function myFunction() {
value="Donald"><br>
var x = document.forms["frm1"];
Last name: <input type="text" name="lname"
value="Duck"><br><br> var text = "";
<input type="submit" value="Submit"> var i;
</form> for (i = 0; i < x.length ;i++) {
text += x.elements[i].value + "<br>";
<p>Click "Try it" to display the value of each element }
in the form.</p>
document.getElementById("demo").innerHTML
= text;
<button onclick="myFunction()">Try it</button>
}
</script>
<p id="demo"></p>
JavaScript HTML DOM - Changing CSS