「JavaScript」hasAttribute関数で属性値があるか確認する

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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
hasAttributeは指定の要素が指定の属性を持つか否かを示す真偽値を返します。
hasAttributeは指定の要素が指定の属性を持つか否かを示す真偽値を返します。
hasAttributeは指定の要素が指定の属性を持つか否かを示す真偽値を返します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<body>
名前:<input type="text" id="username" value="山田" maxlength="10" >
<br><input type="button" value="検証" onclick="confirm()">
<script>
function confirm(){
// getElementByIdで要素を取得
const username = document.getElementById("username");
// テキストボックスの属性のmaxlengthを削除
if (username.hasAttribute("maxlength")){
console.log("maxlength属性値があります");
}
}
</script>
</body>
</html>
<!DOCTYPE html> <html> <body> 名前:<input type="text" id="username" value="山田" maxlength="10" > <br><input type="button" value="検証" onclick="confirm()"> <script> function confirm(){ // getElementByIdで要素を取得 const username = document.getElementById("username"); // テキストボックスの属性のmaxlengthを削除 if (username.hasAttribute("maxlength")){ console.log("maxlength属性値があります"); } } </script> </body> </html>
<!DOCTYPE html>
<html>
<body>

名前:<input type="text" id="username" value="山田" maxlength="10" >
<br><input type="button" value="検証" onclick="confirm()">

<script>
function confirm(){
    // getElementByIdで要素を取得
      const username = document.getElementById("username");
    // テキストボックスの属性のmaxlengthを削除
      if (username.hasAttribute("maxlength")){
            console.log("maxlength属性値があります");
      }
}
</script>

</body>
</html>

実行結果
「検証」ボタンを押下と、コンソール画面に「maxlength属性値があります」が表示されます。

JavaScript

Posted by arkgame