第一篇文章有提到可以用 document.getElementById()
的方式选取 id
元素渲染到网页,但如果今天我想选取的不只是 id
元素,还有 class
元素或者标籤
这时候可以使用到 .querySelector()
的方式,他就不仅仅只局限于 id
元素
只是在使用 .querySelector()
的时候,选取器的方式要像 css
的方式一样
当选取 id
元素时:
document.querySelector('#title');
当选取 class
元素时:
document.querySelector('.title');
都要有相对应的 #
或者 .
竟然都已经有学到变数了,这时候我们就可以宣告一个变数,专门来储存我们要选取的元素,日后同一个元素需要使用到很多方法时就会方便很多,例如:
var el = document.querySelector('#title');el.textContent = 'Hello World!';
这样的程式码,相对跟下面的程式码相比会比较简洁易懂
document.querySelector('#title').textContent = 'Hello World!';
下一篇将讲到 .querySelectorAll()
以及跟 .querySelector()
的差异性