「jQuery」.childrenで指定要素の子要素を取得する

2022年2月18日

環境
jquery 3.6.0

書式
$(セレクタ名).children(タグ名);
.childrenを使用して指定した要素の子要素(直下のみ)を取得します。
使用例

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(){
// div#tt要素の直下子要素がpタグの要素を取得します
$('#btnReg').click(function(){
var $obj = $("div#tt").children("p");
$obj.each(function(){
alert($(this).text());
});
});
});
</script>
</head>
<body>
<input type="button" id="btnReg" value="取得">
<div id="tt">
<p>東京</p>
<div><p>大阪<p></div>
<p>福岡</p>
</div>
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script> $(function(){ // div#tt要素の直下子要素がpタグの要素を取得します $('#btnReg').click(function(){ var $obj = $("div#tt").children("p"); $obj.each(function(){ alert($(this).text()); }); }); }); </script> </head> <body> <input type="button" id="btnReg" value="取得"> <div id="tt"> <p>東京</p> <div><p>大阪<p></div> <p>福岡</p> </div> </body> </html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(){
// div#tt要素の直下子要素がpタグの要素を取得します
  $('#btnReg').click(function(){
     var $obj = $("div#tt").children("p");
     $obj.each(function(){
       alert($(this).text());
    });
  });
});
</script>
</head>
<body>
<input type="button" id="btnReg" value="取得">
<div id="tt">
  <p>東京</p>
  <div><p>大阪<p></div>
  <p>福岡</p>
</div>
</body>
</html>

 

jQuery

Posted by arkgame