ちょっと、まだ起動していない要素にjavascriptでクラスを追加する方法がありますか?私はまだ存在しないクラスにCSSを追加する
$(".myelement).attr('class', 'myelement toast');
を使用MYELEMENTが私のコードで表示されますいけないので、私は一度それを立ち上げまでクラスが適用されていませんか?
ちょっと、まだ起動していない要素にjavascriptでクラスを追加する方法がありますか?私はまだ存在しないクラスにCSSを追加する
$(".myelement).attr('class', 'myelement toast');
を使用MYELEMENTが私のコードで表示されますいけないので、私は一度それを立ち上げまでクラスが適用されていませんか?
チェックこれは: - 非表示または非存在
let exist = false;
document.body.addEventListener("DOMSubtreeModified", function() {
// http://caniuse.com/#search=DOMSubtreeModified
// warning : this will run everytime the dom modified
// this check will prevent unwanted loops
if(!exist) {
setTimeout(function() {
const theDiv = document.getElementById('theDiv');
if(theDiv && !exist) {
exist = true;
console.log("It is right there, let's add a class to it");
// add some delay (not a must, just to follow easily)
setTimeout(function() {
theDiv.setAttribute('class', theDiv.getAttribute('class')+' cool');
console.log('done!')
},1000);
}
},0);
}
});
console.log("Waiting 2 seconds...");
// delay to follow things easily
setTimeout(function() {
console.log("Creating a div..");
let newDiv = document.createElement('div');
newDiv.innerHTML = 'Cool!';
newDiv.setAttribute('id','theDiv');
document.body.appendChild(newDiv);
console.log("Created.");
},2000);
.cool {
background-color: red;
color: white;
font-weight: bold;
}
絶対に正しい:DOMにまだ含まれていない要素に属性、データ、プロパティなどを追加することはできません。
「.myelement」ノードが作成され、ページに追加されるたびにその呼び出しを行う必要があります。
ところで、CSSクラスでは、 "attr"を使用しないでください - 代わりにjQuery's class methodsを使用してください。
希望すると便利です。
*まだ*起動しませんか? – RomanPerekhrest
要素はどこに 'document'に追加されていますか? – guest271314
新しいコードを追加したモジュールを使用するまでは表示されません! – psppro26