getElementById
<div id="foo">...</div>
という要素を取得したい場合は、document.getElementById('foo')
と実行することでその要素を取得できます。もし、存在しない場合はnull
になります。
querySelector と querySelectorAll
CSS のセレクタで要素を取得できます。querySelector
は対象の要素かnull
が、querySelectorAll
は対象の要素の配列(無ければ空配列)を返します。
document.querySelector('.foo');
document.querySelectorAll('.foo, [data-testid="bar"]');