DOM Flashcards

1
Q

How to get the element on the page if you know the id?

A

getElementById() method of document’s object.

var myEl = document.getElementById(“idOfTheElement”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How to access the HTML that is inside of the tags of an HTML element?

A

innerHTML property of element object.

var innHTML = document.getElementById(“myElem”).innerHTML;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

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>

?

A

Use setAttribute() method of the html element’s object.

document.getElementById(“myDiv”).setAttribute(“class”, “myClass”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

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”?

A

Use getAttribute() method of html’s element object:

var attrValue = document.getElementById(“coolDiv”).getAttribute(“class”);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How can you execute the function after the html page loads?

A

Use window’s object onload property.

Like so

function executeWhenPageLoaded(){
//function's code
}

window.onload = executeWhenPageLoaded;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What will be displayed in the console and why?

console.log(document.getElementById(“board”).getAttribute(“class”));

<div class="myClass"> </div>
A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly