Document Object Model methods used for selecting elements on a web page
Elements are represented by objects which contains useful properties and methods for working with them.
getElementById
– get element by their id
Fastest and easiest way of selecting something from the page is by select using
the element associated with the element.
1 2 3 4 |
<header> <h1 id="mainHeading"><p>JavaScript Fundamentals</p></h1> <h2>Part of the Front End Development learning path by Tuts+</h2> </header> |
Notice we have id “mainHeading” in the h1 element.
We can use
1 |
console.log(document.getElementById('mainHeading'); |
result:
1 |
<h1 id="mainHeading"><p>JavaScript Fundamentals</p></h1> |
getElementsByClass
– Get collection of elements by class name.
Given,
1 2 |
<h1 class="heading" id="mainHeading"><p>JavaScript Fundamentals</p></h1> <h2 class="heading">Part of the Front End Development learning path by |
We use
1 |
console.log(document.getElementsByClassName('heading'); |
results:
[h1#mainHeading.heading, h2.heading.subHeading, mainHeading: h1#mainHeading.heading]
getElementsByTagName
html:
1 2 3 4 5 6 7 8 9 |
<body> <header> <h1 class="heading" id="mainHeading"><p>JavaScript Fundamentals</p></h1> <h2 class="heading subHeading">Part of the Front End Development learning path by Tuts+</h2> </header> <a href="history.html">History</a> <a href="#">empty</a> <script src="js/elements.js"></script> </body> |
1 |
console.log(document.getElementsByTagName('a')); |
result:
[a, a]
getElementsByName
html:
1 |
<a name='historyLink' href="history.html">History</a> |
js:
1 |
console.log(document.getElementsByName('historyLink')); |
result:
[a]