Document.getElementById (...). setAttribute ("style", ... does not work in Internet Explorer

document.getElementById (...). setAttribute ('style', ... does not work in Internet Explorer 7.0. How can I make this work in Internet Explorer?

<!DOCTYPE html> <html lang="en"> <head> <script type="text/javascript"> var myarray=new Array(3); for (i=0; i <1000; i++){ myarray[i]=new Array(3); } myarray[0][0]="new"; myarray[0][1]="old"; function swapText(id){ document.getElementById('id' + id).setAttribute('style', 'font-weight: bold; color: red; font-size:150%;'); document.getElementById('id'+ id).innerHTML = myarray[id][0]; } function originalText(id){ document.getElementById('id' + id).setAttribute('style', 'color:' + 'black' + ';'); document.getElementById('id' + id).innerHTML = myarray[id][1]; } </script> </head> <body> <div id="scoreboard" border='1'> </div> <div id="qa"> <div id="col1" class="column"> <div id="id0" onmouseover="swapText(0)"; onmouseout="originalText(0)">old</div> </div> </div> </body> </html> 
+4
source share
4 answers

Using setAttribute is unreliable if you want changes reflected in the document. Use Element.style instead:

 var el = document.getElementById('id' + id); el.style.fontWeight = 'bold'; el.style.color = 'red'; el.style.fontSize = '150%'; 

etc.

+16
source

Use jQuery .

jQuery is a very powerful JavaScript library that allows you to do almost anything with very little code. One of the main advantages (with the exception of its beautiful syntax) is that it is specially designed as independent of the platform and browser, so you no longer have to worry about it.

Doing what you are doing now, but in jQuery, might look something like this:

 function swapText(id) { $('#id' + id) .css('font-weight','bold').css('color','red').css('font-size','150%') .html(myarray[id][0]); } function originalText(id) { $('#id' + id).css('color','black').html(myarray[id][1]); } 

Of course, if you define a CSS class for your โ€œmodifiedโ€ style, you can simply use $('#id'+id).addClass('swapped'); and $('#id'+id).removeClass('swapped'); .

In addition, there are really good ways to hook events, so you donโ€™t even need to define functions with names if you don't want to:

 $('div').hover(function() { $(this) .css('font-weight','bold').css('color','red').css('font-size','150%') .html(myarray[id][0]); }, function() { $('#id' + id).css('color','black').html(myarray[id][1]); }); 
+1
source

From MSDN : This attribute is not available through scripts. To access styles with scripts, use a style object

0
source

you can use setAttribute which is also compatible with IE-8 and IE-7

  var el = document.getElementById('id' + id); el.setAttribute('fontWeight','bold'); el.setAttribute('color','red'); el.setAttribute('fontSize','150%'); 

to assign a class to an element, I suggest the following

  el.className = "class-name"; 
0
source

All Articles