简体   繁体   中英

set attribute for dynamically created class not working in javascript

http://jsfiddle.net/55Lht7hu/

I am trying to add a attribute (dynamically created) to a div. But it is not working here.

var style3=createElement('style');
style3.type="text/css";
var target3=document.getElementById('target3');
target3.addEventListener('click',function(){

style3.innerHTML='.target4{background-color:#444;}';
document.getElementsByTagName('head')[0].appendChild(style3);
target3.setAttribute('class','target4');

});

Also, is it possible to set pseudo elements dynamically to that div?.

First of all there is no such global function createElement , you should use method of the document object:

var style3 = document.createElement('style');

Then, in order your new background color to be applied, you need to make rule priority higher, because class selector .target4 will not beat id selector #target3 . You can increase selector weight for example by prefixing it with corresponding element id selector: #target3.target4 .

Final clean up, you can drop style3.type="text/css"; as it's anyway default type for style element.

All together:

 var style3 = document.createElement('style'); var target3 = document.getElementById('target3'); target3.addEventListener('click', function () { style3.innerHTML = '#target3.target4 {background-color:#444;}'; document.head.appendChild(style3); target3.setAttribute('class', 'target4'); }); 
 #target3 { width:100px; height:200px; background:red; } 
 <body> <div id="target3"></div> </body> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM