JavaScriptでstyle属性を追加する方法を以下のページに書きました。
例えば、その追加したstyle属性は特定の位置までスクロールしたときや、ボタンを押されたときなど「何かのタイミングで属性を削除したい」ことがあります。
そんなときは「removeAttribute」を使えばできます。
JavaScriptで特定の要素のstyle属性を削除する方法
codepenでサンプルを作りました。「remove attr」ボタンを押すと、「box」の文字が小さくなって背景色がなくなります。
インラインスタイルで書かれているstyle属性「style=”font-size:2rem; background:#eee;”」が削除されました。
html
<button id="removebutton" onclick="removeattr()">remove attr</button> <div id="box" style="font-size:2rem; background:#eee;">box</div>
JavaScript
function removeattr(){
let box = document.getElementById('box'); //id「box」要素を取得
box.removeAttribute('style'); //style属性を削除
}
CSS
body{
text-align:center;
}
button{
margin-bottom:1rem;
}
他の属性も削除できるよ
今回は、例としてstyle属性を削除する方法を書きましたが、他の属性も削除できます。
name属性を削除
element.removeAttribute('name');
title属性を削除
element.removeAttribute('title');
など「removeAttribute」に削除したい属性を指定すればOKです。
このページを共有する