「Javascript」hasAttributeで属性値があるか確認するサンプル

2021年12月13日

書式
var result = element.hasAttribute(attName);
result : true または false の戻り値を保有
attName : 属性の名前を表す文字列を指定

使用例

<input type="text" id="username" value="山田" maxlength="15" >
<!--ボタンを押すと、funA関数を呼び出します -->
<input type="button" value="検証" onclick="funA()">
<script>
function funA(){
      const cft = document.getElementById("username");
  // 属性のmaxlengthが存在するか判定
      if (cft.hasAttribute("maxlength")){
            alert("属性maxlengthがあります");
      }
}
</script>

実行結果
「検証」ボタンを押すと、「属性maxlengthがあります」ダイアログボックスがが表示されます

JavaScript

Posted by arkgame