Back to feed
Renewal·서른의 생활코딩

Sample Source 5) JavaScript Basic Document Structure: DOM (1)

NS
normalstory
cover image


Sample Source 5) JavaScript Basic Document Structure: DOM 





* Concepts to know :: Nodes (a document is a collection of nodes), element nodes, text nodes, attribute nodes

* Elements to know

document.getElementById        // ID only once..

document.getElementsByTagName  //s

ex) document.getElementsByTagName("li");


getAttribute()  : returns the attribute value. // arguments (attribute name)

ex) document.getElementById("photo").getAttribute("src");

setAttribute()  : new value  // arguments (attribute name, new value) 

ex) document.getElementById("photo").setAttribute("src","newPhoto.jpg");




Example) An example you can test that uses DOM to retrieve parts you need from inside the body tag 


<!DOCTYPE html> 

<html> 

<head> 

<meta charset="utf-8"> 

<title>dom test</title>

</head>


<body>

<div id="mv_list">

<h1 class="title1">Movie ranking list</h1>

<ol>

<li class="list1">List 1</li>

<li class="list2">List 2</li>

<li class="list3">List 3</li>

<li class="list4">List 4</li>

</ol>

<h1 class="title2">Upcoming movie list</h1>

<ul>

<li class="list5">Movie 1</li>

<li class="list6">Movie 2</li>

<li class="list7">Movie 3</li>

<li class="list8">Movie 4</li>

</ul>

</div>

<script type="text/javascript">

//<![CDATA[

//1

document.write(document.getElementById("mv_list").parentNode.nodeName+"<br />");

//2

document.write(document.getElementById("mv_list").childNodes[0].nodeName+"<br />");

document.write(document.getElementById("mv_list").childNodes.item(1).nodeName+"<br />");

//3

document.write(document.getElementById("mv_list").firstChild.nodeName+"<br />");

document.write(document.getElementById("mv_list").childNodes[0].nodeName+"<br />");

//4

document.write(document.getElementById("mv_list").lastChild.nodeName+"<br />");

//5

document.write(document.getElementsByTagName("li")[1].previousSibling.className+"<br />");

document.write(document.getElementsByTagName("li")[1].nextSibling.className+"<br />"); 

//]]>

</script>

</body>

</html> 

This English version was translated by Claude.

친절한 찰쓰씨
Written by
친절한 찰쓰씨

Pleasant Charles — UI/UX researcher at AIT. Keeping notes on design, planning, and slow days here since 2010.

More on the author's page

Keep reading

Renewal

Steadily, for the long haul, without burning out

Mar 31, 2026·9 min
Renewal

Tech-life balance

Feb 7, 2026·3 min
Renewal

Humanality, by Park Jeong-ryeol

Feb 7, 2026·11 min