기록하는 개발자

[JavaScript] js 에서 html의 element 사용하기 본문

Web/Javascript

[JavaScript] js 에서 html의 element 사용하기

밍맹030 2021. 7. 28. 15:42
728x90

<HTML>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet", href="style.css">
    <title>Momentum</title>
</head>
<body>
    <div class="fruit">
        <h1 id="first">Peach🍑</h1>
    </div>

    <div class="fruit">
        <h1 id="second">GreenApple🍏</h1>
    </div>

    <div class="fruit">
        <h1 id="third">WaterMelon🍉</h1>
    </div>

    <br>
    <div id="weather">
        <h2>☁</h2>
        <h2>🌞</h2>
        <h2>☃</h2>
        <h2>☔</h2>
    </div>

    <script src="app.js"></script>
</body>
</html>

<CSS>

body{
    background-color: lightblue;
    text-align: center;
}​

<js 적용 이전 화면>

// document : 현재 js 파일과 연결된 html 파일
// document에 first 라는 id를 가진 element를 가져온다.
let firstElement=document.getElementById("first"); 
console.log(firstElement);

// document에 second 라는 id를 가진 element의 innerText를 가져온다.
let SecondElement=document.getElementById("second").innerText; 
console.log(SecondElement);

let ThirdElement=document.getElementById("third"); 
ThirdElement.innerText="Corn🌽"
console.log(ThirdElement);


//querySelector 에 해당하는 첫 번째 내용만 가져온다.
let temp=document.querySelector("h1"); 
console.log(temp);

//querySelector 에 해당하는 모든 내용을 가져온다.
temp=document.querySelectorAll(".fruit h1"); 
console.log(temp);

/*아래 두 줄은 같은 일을 한다.
querySelector 에서는 css selector 자체를 전달하므로 
id를 가져옴을 명시하기위해 # 사용*/
temp=document.getElementById("weather"); 
console.log(temp);
temp=document.querySelector("#weather"); 
console.log(temp);

<위 js 파일 적용 후 화면>

<console.log가 실행된 모습> 

 

→ first 라는 id를 가진 element를 가져온다.

let firstElement=document.getElementById("first"); 
console.log(firstElement);

 

→ second라는 id를 가진 element의 innerText를 가져온다.
let SecondElement=document.getElementById("second").innerText; 
console.log(SecondElement);

 

→ third라는 id를 가진 element의 innerText를 변경한다.
let ThirdElement=document.getElementById("third"); 
ThirdElement.innerText="Corn🌽"
console.log(ThirdElement);


→ querySelector 에 해당하는 첫 번째 내용만 가져온다.
let temp=document.querySelector("h1"); 
console.log(temp);

→ querySelector 에 해당하는 모든 내용을 가져온다.
temp=document.querySelectorAll(".fruit h1"); 
console.log(temp);

 

→ 아래 두 코드는 같은 일을 한다.

    결과적으로 console 창에 동일한 내용이 출력되었다.

temp=document.getElementById("weather"); 
console.log(temp);
temp=document.querySelector("#weather"); 
console.log(temp);

 

 

 

728x90