Software Study/Javascript

[2021.01.27] JavaScript 공부

욜스터 2021. 1. 27. 17:58
728x90

getElementById()

Change HTML content

document.getElementById("demo").innerHTML = "Hello JavaScript";

finds HTML element (with id="demo") and changes the elemtn content (innerHTML) to "Hello"

 

<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick='document.getElementById("demo").innerHTML = "Hello JavaScript!"'>Click Me!</button>

</body>
</html>

 

*javascript accepts both double and single quotes

 

Change HTML Attribute Values

"document.getElementById('myImage').src='pic_bulbon.gif'"

changes the value of the src (source) attribute of an <img> tag

 

<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button>

 

Change HTML Style (CSS)

document.getElementById("demo").style.fontSize = "35px";

 

Hide HTML Elements

document.getElementById("demo").style.display = "none";

 

Show HTML Elements

document.getElementById("demo").style.display = "block";

 

<p id="demo" style="display:none">Hello JavaScript!</p>

<button type="button" onclick="document.getElementById('demo').style.display='block'">Click Me!</button>

 

 

 

The <script> Tag

In HTML, JavaScript code is inserted between <script> and </script> tags.

It can be placed in the <body>, or in the <head> section, or in both.

 

 

 

Functions and Events

function is invoked (called) when a button is clicked:

<!DOCTYPE html>
<html>
<body>

<h1>A Web Page</h1>
<p id="demo">A Paragraph</p>
<button type="button" onclick="myFunction()">Try it</button>

<script>
function myFunction() {
  document.getElementById("demo").innerHTML = "Paragraph changed.";
}
</script>

</body>
</html>

*placing scripts at the bottom of the <body> element improves the display speed

 

 

External JavaScript

Scripts can be placed in external files

-myScript.js

function myFunction(){
	document.getElementById("demo").innerHTML = "Paragraph changed.";
}

 

To use an external script, put the name of the script file in the src (source) attribute of a <script> tag:

src에 파일이름 적어주면됨.

<script src="myScript.js"></script>

외부파일 사용의 장점: HTML과 구분가능, 읽는게 편함, 페이지 로딩속도 빨라짐

 

 

scripts can be referenced with a full URL

<script src="https://www.w3schools.com/js/myScript1.js"></script>

 

728x90
반응형

'Software Study > Javascript' 카테고리의 다른 글

[2021.01.29] JavaScript 공부  (0) 2021.01.29