innerText/ innerHTML을 이용한 요소 내용(content) 입/출력
innerText
: 요소에 작성된 내용을 읽거나 변경할 때 innerText 속성을 사용한다.
<body>
<button onclick="check1();"> innerText 확인하기</button>
<button onclick="check2();"> innerHTML 확인하기</button>
<!-- internal방식 -->
<script>
function check1(){
const area1 = document.getElementById("area1");
}
</script>
</body>
document
: 현재 웹 문서( 현재 HTML )
.getElementById("id명")
: 현재 문서 내에서 id 속성값이 "area1"인 요소를 얻어왔다(== 선택했다)
const area1
: 상수형 변수 area1 선언
➡ 현재 문서 내에서 id속성 값이 "area1"인 요소를 얻어와 상수형 변수 area1에 대입
console.log(area1); 로 설정해두면 자동으로 console창에 뜬다.

console.log( area1.innerText);

console.log( area1.innerText );

area1.innerHTML = "<h3>innerText의 setter 용도 사용법을 이용해 내용 변경</h3>"


➡ innetText 라는 변수(속성)이 있고 여기에 대입, 출력하는 방식이라고 생각하면 쉽다.
버튼 클릭 시 요소의 내용 변경된다
추가)
글자 태그를 넣어도 태그가 아닌 문자 자체로 인식되어 출력된다.
그러나 innerHTML에서는 태그로 인식해서 적용된다.
innerHTML
: innerHTML도 요소에 작성된 내용을 읽거나 변경할 때 사용하나
innerText와 다르게 요소에 작성된 태그 + 속성 + 내용을 모두 읽거나 변경한다.
console.log(area2);

// area2 요소에 작성된 내용만 얻어와 console에 출력
console.log(area2.innerHTML);

<br> 태그가 읽어진 것을 확인할 수 있다.
area2.innerHTML = "<hr><h3>innerHTML을 setter로 사용했다.</h3>"


area2.innerHTML = "<input type ='text' size='20'>";


window.confirm("내용")을 이용한 데이터 입력
<button onclick="testConfirm();"> confirm확인 버튼 </button>
<div id="area4"></div>
<button onclick="testConfirm2();">confirm 확인 버튼 2</button>
<script>
function testConfirm(){
console.log( window.confirm("확인/취소 버튼 중 하나를 클릭하세요"));
// window는 브라우저 창 자체를 의미하는데 생략 가능하다
}
function testConfirm2(){ // 윈도우 생략
const result = confirm("오늘 점심을 드시겠습니까?");
const area4 = document.getElementById("area4");
// 문서내에서 id가 area4인 값을 가져와서 상수 area4에 대입
if(result){ // 확인을 누른 경우
area4.innerHTML = "<h4 style='color : darkgreen'>맛점맛점</h4>";
} else { //취소를 누른 경우
area4.innerHTML = "<h4 style='color : darkblue'>꿀잠</h4>";
}
}
</script>
testConfirm()


testConfirm2()



window.ptompt()를 이용한 데이터 입출력
prompt : 즉시 값을 입력하는 도구
-> JS에서는 값을 입력 받아 바로 반환해주는 역할
<button onclick="testPrompt();">prompt 확인 버튼</button>
<button onclick="testPrompt2();">prompt 확인 버튼2</button>
<div id="area5"></div>
<script>
function testPrompt(){
console.log( window.prompt("아무거나 입력하세요."));
}
function testPrompt2(){
// 결과를 출력할 요소를 미리 얻어오기
const area5 = document.getElementById("area5");
// 이름 또는 null이 저장
const input = prompt("이름을 입력해주세요.");
if(input != null) {
area5.innerHTML = "<h3>" + input + "님 환영 합니다.</h3>";
} else {
area5.innerHTML = "<h3> 취소되었습니다.</h3>" //input값이 없으니 바로 태그 작성
}
}
</script>
testPrompt()


입력 후 확인 시 값이 입력, 취소 시 null
testPrompt2()



'Frontend > JavaScript' 카테고리의 다른 글
[Javascript] 07 이벤트, 이벤트리스너,이벤트핸들러 /인라인·고전·표준모델 (0) | 2021.11.16 |
---|---|
[Javascript] 문자열,숫자,형변환,연산자 (0) | 2021.11.15 |
[Javascript] 변수 선언 , 자료형 (0) | 2021.11.11 |
[Javascript] 요소접근방법 (0) | 2021.11.08 |
[Javascript] 1_개요, inline, internal, external (0) | 2021.11.04 |