2017-11-15 7 views
1

私はCodepenを試していますが、Spanの背景色をHTMLのName属性の値に変更したいと考えています。私はこれまで午前どこ背景属性の値をName属性の値に変更する

次Codepenは示しています。

私は間違っているつもりです

https://codepen.io/anon/pen/JOymve?editors=1010

<div class="card-body"> 
    <span id="community" class="card-community-tag" Name="test">Community 1</span> 
    <span class="card-community-tag">Community 2</span> 
</div> 

document.load(function changeBackground() { 
    var communityName = document.getElementById("community"); 
    if (communityName.getAttribute("Name") == "test") { 
     communityName.style.backgroundColor = "red"; 
    } 
}); 

最終的な目標は、JSがそのスパンの名前属性をチェックして、そのスパンの背景色を決定することです。

おかげで、代わりにdocument.load()

トム

+0

移動をdocument.load' https://codepen.io/koliada 'から/ pen/POKVBP?editors = 1111 –

答えて

1

使用document.addEventListener('DOMContentLoaded', function() {})MDN):

document.addEventListener('DOMContentLoaded', function() { 
 
    var communityName = document.getElementById("community"); 
 
    if (communityName.getAttribute("Name") == "test") { 
 
     communityName.style.backgroundColor = "red"; 
 
    } 
 
});
<div class="card-body"> 
 
    <span id="community" class="card-community-tag" Name="test">Community 1</span> 
 
    <span class="card-community-tag">Community 2</span> 
 
</div>

1

あなたの問題は、このラインは

0123です

loadまたはonloadはもはや今ではDOMContentLoadedイベント(pen更新)あなたがloadを呼び出すしよう

document.addEventListener("DOMContentLoaded", function() { 
0

を扱う変更のブラウザでサポートされていませんが、あなたはonloadを探しています。

function changeBackground() { 
    var communityName = document.getElementById("community"); 
    if (communityName.getAttribute("Name") == "test") { 
    communityName.style.backgroundColor = "red"; 
    } 
} 

document.onload = changeBackground(); 

注:JS内のCSSを直接​​変更するよりも、CSSクラス名を変更する方が効果的です。

communityName.className += ' red'; 
1

ドキュメントの負荷リスナーのためにこれを使用してみてください:そう

document.addEventListener("DOMContentLoaded", function(event) { 
    // Do the business 
}); 

:あなたのコード実行

document.addEventListener("DOMContentLoaded", function(event) { 
    var communityName = document.getElementById("community"); 
    if (communityName.getAttribute("Name") == "test") { 
    communityName.style.backgroundColor = "red"; 
    } 
}); 
関連する問題