https://www.guru99.com/how-to-use-dom-and-events-in-javascript.html

 

JavaScript DOM Tutorial with Example

In this example program, we will reverse a string entered by a user. We will create a function to...

www.guru99.com

 

DOM ( Document Object Model ) 

이게 돔이다.

 

HTML이 돔인가 ? 아니다. 

웹 브라우저들은 페이지를 로드할 때 트리구조로 돔을 만든다. 브라우저에 의해 트리구조로 변경된게 바로 DOM이다.

JS는 웹 페이지에 있는 모든 엘리멘트들에 접근 할 수 있다. DOM을 사용하면서 말이다. 돔을 사용하면서 엘리멘트와 속성값을 만들고 바꾸고 제거한다. 또한 이벤트를 작동시키고 새로운 이벤트를 만들기도 한다.

<html>
<head>
	<title>DOM!!!</title>
</head>
<body>
  <h1 id="one">Welcome</h1>
  <p>This is the welcome message.</p>
  <h2>Technology</h2>
  <p>This is the technology section.</p>
  
  <script type="text/javascript"> 
  <!-- JS 코드 -->
		var text = document.getElementById("one").innerHTML;
		alert("The first heading is " + text);
  </script>
  
</body>
</html>

위의 코드를 보면 html로 만들어진 페이지에 여러 엘리멘트들이 있다. 

여기서 JS는 getElementById()와 innerHTML을 통해 특정 id의 엘리멘트에 접근하고 있다.

id 말고 tag로 접근 할 수 도 있다.

<html>
<head>
	<title>DOM!!!</title>
</head>
<body>
  <h1>Welcome</h1>
  <p>This is the welcome message.</p>
  <h2>Technology</h2>
  <p id="second">This is the technology section.</p>
  
  <script type="text/javascript">
	var paragraphs = document.getElementsByTagName("p"); 
    alert("Content in the second paragraph is " + paragraphs[1].innerHTML);
    document.getElementById("second").innerHTML = "The orginal message is changed.";
  </script>
  
</body>
</html>

getElementsByTagName() 을 통해 2번째 p 태그의 속성값을 바꿨다.

 

뭐 이런것들이 있다.

 

+ Recent posts