DOM Flashcards
How to get the element on the page if you know the id?
getElementById() method of document’s object.
var myEl = document.getElementById(“idOfTheElement”);
How to access the HTML that is inside of the tags of an HTML element?
innerHTML property of element object.
var innHTML = document.getElementById(“myElem”).innerHTML;
How to set the value of an HTML element’s attribute?
For example, if you have a tag <div> </div>
How can you make the html like so:
<div></div>
?
Use setAttribute() method of the html element’s object.
document.getElementById(“myDiv”).setAttribute(“class”, “myClass”);
How to get the value of a certain HTML element’s attribute?
For example, if you have a tag <div class="someClass"> </div>
How can you get the value “someClass”?
Use getAttribute() method of html’s element object:
var attrValue = document.getElementById(“coolDiv”).getAttribute(“class”);
How can you execute the function after the html page loads?
Use window’s object onload property.
Like so
function executeWhenPageLoaded(){ //function's code }
window.onload = executeWhenPageLoaded;
What will be displayed in the console and why?
console.log(document.getElementById(“board”).getAttribute(“class”));
<div class="myClass"> </div>
Uncaught TypeError: Cannot read property ‘getAttribute’ of null
JavaScript code in this case runs before the page is loaded, so document.getElementById(“board”) is null
To fix this, you need to make the JavaScript code run after the page is loaded.