2

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?.

arvind
  • 157
  • 2
  • 11

1 Answers1

0

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>
dfsq
  • 191,768
  • 25
  • 236
  • 258