프로그래밍 문법/javascript

HTML에서 작성한 내용을 JS에서 수정하기

씩씩한 IT블로그 2022. 6. 5. 13:36
반응형

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="divClass">
            <h1 class="h1Class" id="line1">this is h1 1</h1>
            <h1 class="h1Class">this is h1 2</h1>
            <h1 class="h1Class">this is h1 3</h1>
            <h1 id="clickChangeColor">click to change color</h1>
            <h1 id="clickChangeClass">click to change class</h1>
            <h1 id="mouseOver">mouse over</h1>
            <h2>this is h2</h2>
            <h3>this is h3</h3>
        </div>   
        <h2>this is h2(out of div)</h2>
        <script src="app.js"></script>
    </body>
</html>

 

JS코드

// -------------------------------[불러오기]-------------------------------
// 1. id로 불러오기
const callById = document.getElementById("line1"); 
console.log(callById);
console.log("className : ",callById.className);
console.log("innerText : ",callById.innerText);
console.dir(callById);

callById.innerText="(updated)this is h1 1"; //line1의 글자를 grab me-> got you로 바꿈

// 2. 클래스이름으로 불러오기
const calByClass = document.getElementsByClassName("divClass");
console.log(calByClass); 

// 3. tag로 불러오기
const callByTag = document.getElementsByTagName("h2")
console.log(callByTag)
 
// 4. 쿼리사용, 추천하는 방법
const callByQuery = document.querySelector("h1.h1Class");
console.log(callByQuery)

 

콘솔창

반응형