아래 예시에서 document.getElementById("demo")
줄이 어떤 기능을 하는지 설명해 주시겠어요?
getElementById가 데모의 아이디를 가져온다는 건 알겠는데, 이 코드에서 <p id="demo"></p>
가 정확히 무엇을 하는 건가요?
문서.getElementById("age")`는 입력인 나이의 아이디를 가져오기 때문에 명확합니다.
function myFunction() {
var age,voteable;
age = document.getElementById("age").value;
voteable = (age < 18)? "Too young" : "Old enough";
document.getElementById("demo").innerHTML = voteable;
}
<p>Click the button to check the age.</p>
Age:<input id="age" value="18" />
<p>Old enough to vote?</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
고려 사항
var x = document.getElementById("age");
여기서 x
는 id="age"
를 가진 요소입니다.
이제 다음 줄을 보세요.
var age = document.getElementById("age").value;
이는 id="age"
를 가진 요소의 값을 가져오고 있음을 의미합니다.
getElementById는
id`를 사용하여 요소에 대한 참조를 반환합니다. 요소는 첫 번째 경우에는 '입력'이고 두 번째 경우에는 단락입니다.
https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById