jQuery :firstで最初のInput要素を操作するサンプル

環境
Google Chrome 111.0.5563.65(Official Build)
Windows 10 Home 64bit
jquery 3.6.3

書式
$(“input:first").css(属性名,値);
最初のInput要素のCSSを変更します

使用例

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.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// ボタンのイベント
$("#chk").click(function(){
//最初のInput要素の取得
$("input:first").css("background","green");
});
});
</script>
</head>
<body>
<p><input type="text" id="cityA" value="tokyo"></p>
<p><input type="text" id="cityB" value="oosaka"></p>
<p><input type="text" id="cityC" value="fukuoka"></p>
<button id="chk">検証</button>
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script> <script> $(document).ready(function(){ // ボタンのイベント $("#chk").click(function(){ //最初のInput要素の取得 $("input:first").css("background","green"); }); }); </script> </head> <body> <p><input type="text" id="cityA" value="tokyo"></p> <p><input type="text" id="cityB" value="oosaka"></p> <p><input type="text" id="cityC" value="fukuoka"></p> <button id="chk">検証</button> </body> </html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
  // ボタンのイベント
  $("#chk").click(function(){
        //最初のInput要素の取得
        $("input:first").css("background","green");
  });
});
</script>
</head>
<body>
<p><input type="text" id="cityA" value="tokyo"></p>
<p><input type="text" id="cityB" value="oosaka"></p>
<p><input type="text" id="cityC" value="fukuoka"></p>

<button id="chk">検証</button>

</body>
</html>

実行結果
「検証」ボタンを押すと、最初のinput要素(id="cityA")テキストボックスの入力欄の背景色を緑色にします。

CSS

Posted by arkgame