javascript - Cannot understand the behavior of element.style.color -
in following code color of element para1 set green means of internal styling @ beginning.
if click on buttons first time "console.log(elem.style.color)" inside "function changecolor" not return color green. second time , on color of element returned.
function changecolor(newcolor) { var elem = document.getelementbyid("para1"); console.log(elem.style.color); elem.style.color = newcolor; }
.mypara1{ color: green; }
<p id="para1" class="mypara1">some text here</p> <button onclick="changecolor('blue');">blue</button>
why color set internal styling not returned?
the reason elem.style
returns style directly applied on dom element (e.g. in html, or through elem.style
), not style resulting css selector.
if want computed style, takes account css rules, need use window.getcomputedstyle
. note result may different has been entered (e.g. chrome, colors given rgb values).
function changecolor(newcolor) { var elem = document.getelementbyid("para1"); console.log(getcomputedstyle(elem).getpropertyvalue("color")); elem.style.color = newcolor; }
.mypara1{ color: green; }
<p id="para1" class="mypara1">some text here</p> <button onclick="changecolor('blue');">blue</button> <button onclick="changecolor('red');">red</button>
here example style attribute set in html instead of css. see console.log
works first time when using elem.style
.
function changecolor(newcolor) { var elem = document.getelementbyid("para1"); console.log(elem.style.color); elem.style.color = newcolor; }
<p id="para1" class="mypara1" style="color: green;">some text here</p> <button onclick="changecolor('blue');">blue</button> <button onclick="changecolor('red');">red</button>
Comments
Post a Comment