-1

I am having a div and using javascript to set attribute for it with the below code

Javascript

var m = document.getElementById('d1');
m.setAttribute("height","50%"); 

but it throws an error as setAttribute() property cannot be set to the null reference.

My HTML Code

<div id="d1" style:"background-color:blue;"> 
Krish
  • 2,590
  • 8
  • 42
  • 62
Swetha Puthuru
  • 15
  • 1
  • 2
  • 5

3 Answers3

4

Your HTML markup is wrong it should be <div id="d1" style="background-color:blue;">

syntax for setAttribute

element.setAttribute(name, value); 

check attribute reference

so, the javascript code should be

var m=document.getElementById('d1');
m.setAttribute("style","height:50%"); 

because height can be directly applied to the following elements <canvas>, <embed>, <iframe>, <img>, <input>, <object>, <video>

Live Example http://codepen.io/krish4u/pen/bicCL(in example height set to 50px In your case you can use %

Krish
  • 2,590
  • 8
  • 42
  • 62
0
m.setAttribute("style", "height: 50%");
Teh SoTo
  • 209
  • 1
  • 10
0

Better use style instead of setAttribute

m.style.height = "50%";  

It will be:

<div style="height: 50%;"></div>  

But your code is valid and it ouputs:

<div height="50%"></div>
ostapische
  • 1,572
  • 2
  • 12
  • 26