Introduction to DOM manipulation
-
Clone this repo.
-
Open exercise/exercise.js and follow the instructions.
The DOM is the Document Object Model, it is the browser's interpretation of the page once it has been parsed.
In your browser, if you right-click on a page, you see inspect element.
In the image below, article
is a DOM element.
Any html elements you write will be DOM elements in the browser, for example: div
, span
, input
, section
, etc etc.
You can access DOM elements with javascript.
document.getElementById("myId")
returns the element with ID "myId";
<article id="featured-article">
Lorem ipsum...
</article>
<script>
var featuredArticleElement = document.getElementById(#featured-article);
// <article id="featured-article">...</article>
</script>
document.getElementsByClassName("myClass")
returns an array-like object of all elements with the class "myClass";
<li class="menu-item">
London
</li>
<li class="menu-item">
Nazareth
</li>
<script>
var menuItems = document.getElementsByClassName("menu-item");
// [_li.menu-item_,_li.menu-item_]
</script>
document.querySelector(myCssSelector)
returns the first element matching myCssSelector
, where myCssSelector
takes the form of a CSS selector for example "#myId", ".myClass", "myTag", etc etc.
<li class="menu-item">
London
</li>
<li class="menu-item">
Nazareth
</li>
<script>
var firstMenuItem = document.querySelector(".menu-item");
// <li class="menu-item">London</li>
</script>
document.querySelectorAll(myCssSelector)
returns an array-like object of all elements matching myCssSelector.
<li class="menu-item">
London
</li>
<li class="menu-item">
Nazareth
</li>
<script>
var firstMenuItem = document.querySelectorAll(".menu-item");
// [_li.menu-item_,_li.menu-item_];
</script>
We can access properties of DOM elements using javscript.
<section id="featured-section" class="highlight">
<p>Lorem ipsum...</p>
</section>
<script>
document.querySelector("#featured-section").className; // "featured-section highlight"
</script>
What are object properties in javascript?
Here is a list of the DOM element properties