「JavaScript」removeAttribute関数で属性値を削除する

環境
Google Chrome 100.0.4896.127

書式
const 変数名 = document.getElementById(セレクタID名);
変数名.removeAttribute(属性タグ名);
removeAttributeを使って属性値を削除します。

使用例

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="deltag()">
<script>
function deltag(){
// getElementByIdで要素を取得
const username = document.getElementById("username");
// テキストボックスの属性のmaxlengthを削除
username.removeAttribute("maxlength");
}
</script>
</body>
</html>
<!DOCTYPE html> <html> <body> 名前:<input type="text" id="username" value="山田" maxlength="10" > <br><input type="button" value="削除" onclick="deltag()"> <script> function deltag(){ // getElementByIdで要素を取得 const username = document.getElementById("username"); // テキストボックスの属性のmaxlengthを削除 username.removeAttribute("maxlength"); } </script> </body> </html>
<!DOCTYPE html>
<html>
<body>

名前:<input type="text" id="username" value="山田" maxlength="10" >
<br><input type="button" value="削除" onclick="deltag()">

<script>
function deltag(){
    // getElementByIdで要素を取得
      const username = document.getElementById("username");
    // テキストボックスの属性のmaxlengthを削除
      username.removeAttribute("maxlength");
}
</script>

</body>
</html>

結果
「削除」ボタンを押下後、maxlengthが削除されています

JavaScript

Posted by arkgame