jQuery toArray()でDOM要素を配列形式で取得する

環境
Google Chrome 106.0.5249.119
Windows 10 Home 64bit
jQuery 3.6.0

構文
$(セレクター名).toArray();
「.toArray()」を使って、オブジェクトから全ての要素(DOM要素)を配列形式で取得します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
$("#btnchg").click(function() {
// 全ての要素(DOM要素)を配列形式
var em = $('li').toArray();
console.log(em)
});
});
</script>
</head>
<body>
<ul>
<li class="to">東京</li>
<li class="oo">大阪</li>
<li class="fu">福岡</li>
</ul>
<button type="button" id="btnchg">確認</button>
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(function(){ $("#btnchg").click(function() { // 全ての要素(DOM要素)を配列形式 var em = $('li').toArray(); console.log(em) }); }); </script> </head> <body> <ul> <li class="to">東京</li> <li class="oo">大阪</li> <li class="fu">福岡</li> </ul> <button type="button" id="btnchg">確認</button> </body> </html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
    $("#btnchg").click(function() {
       // 全ての要素(DOM要素)を配列形式
       var em = $('li').toArray();
       console.log(em)  
      });
});
</script>
</head>
<body>

<ul>
      <li class="to">東京</li>
      <li class="oo">大阪</li>
      <li class="fu">福岡</li>
</ul>
<button type="button" id="btnchg">確認</button>

</body>
</html>

結果確認
「確認」ボタンを押すと、コンソールに [li.to, li.oo, li.fu]と表示されます。

jQuery

Posted by arkgame