LoginSignup
3
1

More than 5 years have passed since last update.

[JS初心者]#4 セレクタAPI編 JavaScriptを学ぶ

Last updated at Posted at 2017-07-21

[JS初心者]#4 セレクタAPI編 JavaScriptを学ぶ

セレクタ(selector)とは?

スタイルを適用する対象のことです。
たとえば、下記で言うと、

<style>
.color-red {
  color: red;
}
</style>

<div class='color-red'>hoge</div>

divは要素名、colorがプロパティ名、となります。

セレクタAPIとは?

指定されたセレクタに対してDOMを取得できるAPIのことです。

<style>
.color-red {
  color: red;
}
</style>

<div class='color-red'>hoge</div>

これで、このdivに対して指定したいときは、
div.color-red
とすれば、指定することができます。

メソッド名 意味
querySelectorAll(selectors) 指定されたselectorsに合った文書中の全ての要素をリスト形式で返却
querySelector(selectors) 指定されたselectorsに合った文書中の最初の要素を返却
  • querySelector(selectors)
<div class='fuga'>fuga</div>
<div>fuga</div>
<script>
window.onload = function() {
  var divElement = document.querySelector('div.fuga');
  window.alert(divElement.innerHTML);
}
</script> 

fugaが出てくると思います。

  • querySelectorAll(selectors)
<div class='fuga1'>fuga1</div>
<div class='fuga2'>fuga2</div>
<div class='fuga3'>fuga3</div>
<script>
window.onload = function() {
  var divElement = document.querySelectorAll('div.fuga1, div.fuga2');
  for (var i = 0; i < divElement.length; i++) {
    window.alert(divElement[i].innerHTML);                                                                                           
  }             
}               
</script>    

fuga1, fuga2のみでてくると思います。

これまでのページ

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1