# JS DOM(一) JavaScript跟HTML一個是程式語言一個是標記語言。兩個是不能彼此干涉的。 我們會去透過瀏覽器的物件來去改變HTML。 而這個讓我們去操作的介面就是 DOM(Document Object Model)藉由他去存取Document(文件)的物件。 ex 首先創立一個html檔案,跟一個js檔,這邊取名叫app.js ```htmlmixed <head> </head> <body> <div id="hello"> world </div> <script src="app.js"></script> <body> ``` 再來是js ```javascript const h = document.getElementById("hello") h.textContent = "456" h.innerHTML ="<h1>111</h1>" ``` 第一行是設一個物件h,讓他存取文件document的id "hello" 第二行是改變id "hello"的文字內容,把它改成123 第三行跟第二行一樣,但他多了一個功能是改變其標籤。 getElementById算是較舊的寫法,還有另外一種寫法querySelector ``` const i = document.querySelector("#hello") ``` querySelector的優點是寫法跟css選取器一樣,你可以很容易選取到你要用的標籤。 例如在html檔設多個li ```htmlmixed <head> </head> <body> <div class="list"> <ul> <li>a</li> <li>b</li> <li>c</li> </ul> </div> <script src="app.js"></script> <body> ``` ```javascript const item = document.querySelector(".list li:nth-child(2)") item.textContent ="x" ``` 這樣第二個li的b會改成x
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up