2017-12-30 29 views
2

CSSファイルには、次のコードがあります。JavaScriptを使用してこのCSS要素を取得する方法(.questions label:before)?

.questions label:before { 
content: attr(letter); 
display: inline-block; 
color: gray; 
} 

JavaScriptのみを使用して(jQueryは好まれません)、このCSS要素を少し変更して、灰色の代わりに白を作成したいと思います。

私たちが.questionsのようなクラス名しか扱っていなかったら、document.getElementsByClassName("questions").style.color = "white"; のようにすることができますが、JavaScriptを使用して.questions label:before全体を選択します。 :before値を取得する

+0

'document.innerHTML + =" "; –

+2

'document.querySelector( '。questions label:before')。style.color = // whatever'を使用することができます。 – magreenberg

+2

[:: beforeと:のようなCSS擬似要素の選択と操作] :jQuery使用後](https://stackoverflow.com/questions/5041494/selecting-and-manipulating-css-pseudo-elements-such-as-before-and-after-usin) – Nisarg

答えて

1

の代わりにあなたはJSを使用して擬似要素を操作することはできませんとしてあなたは、単に別でそれをオーバーライドすることができCSSを変更/ jQueryはDOMの一部ではないので、ここで読むことができます:https://stackoverflow.com/a/21709814/8620333

前{色:210

document.querySelector('.questions label').classList.add('newclass');
.questions label:before { 
 
    content: attr(letter); 
 
    display: inline-block; 
 
    color: gray; 
 
} 
 

 
label.newclass:before { 
 
    color: red; 
 
}
<div class="questions"> 
 
    <label letter="content ">text text</label> 
 
</div>

+1

ありがとうございます:)これは最も簡単な解決策です。また、貢献したすべての人に感謝します。 – NoobCoder

0

使って計算プロパティ、

var color = window.getComputedStyle(
 
\t document.querySelector('.questions label'), ':before' 
 
).getPropertyValue('color'); 
 
console.log(color); 
 

 
function changeColor(){ 
 
    var elem = document.head.appendChild(document.createElement("style")); 
 
    var colors = ['green','blue','red']; 
 
    elem.innerHTML = ".questions label:before {color: "+getRandom(colors)+";}"; 
 
} 
 

 
function getRandom(colors){ 
 
    var random = Math.floor(Math.random() * colors.length); 
 
    return colors[random]; 
 
}
.questions label:before { 
 
content: attr(letter); 
 
display: inline-block; 
 
color: rgb(255, 0, 0); 
 
}
<div class='questions'> 
 
Best 
 
<label letter='one'> Test</label> 
 
West 
 
</div> 
 

 
<input type="button" value="Change" onclick="changeColor()">

I found this source here

+1

しかし、ユーザーはそれを変更する方法を尋ねる –

+0

色を変更するコードも追加されました – C2486

0

は、ここでは1

var yourcss = '.questions label:before{ background-color: green }'; 
 
var yourstyle = document.createElement('style'); 
 

 
if (yourstyle.styleSheet) { 
 
    yourstyle.styleSheet.cssText = yourcss; 
 
} else { 
 
    yourstyle.appendChild(document.createTextNode(yourcss)); 
 
} 
 

 
document.getElementsByTagName('head')[0].appendChild(yourstyle);
.questions label:before { 
 
content: attr(letter); 
 
display: inline-block; 
 
color: gray; 
 
}
<div class="questions"> 
 
    <label letter="green ">Hello World!</label> 
 
</div>

関連する問題