0

I'm stuck with a piece of simple code pls help

<html> <head> <style> #hed{color: green;} </style> </head> <body> <div id="hed"> <p> Another sentimental improvisation. </p> </div> <br /> <input type="button" onclick="chg()" /> <script> var x = document.getElementById('hed') function chg() { if (x.style.color === 'green') { x.style.color = 'blue'; } else {x.style.color = 'red'} } </script> </body> </html>

31st Dec 2017, 10:03 AM
Cole Reizenberg
Cole Reizenberg - avatar
6 Antworten
+ 7
Use getAttribute it solves your issue. https://developer.mozilla.org/en/docs/Web/API/Element/getAttribute <body> <style> #hed{color: green;} </style> <div id="hed"> <p> Another sentimental improvisation. </p> </div> <br /> <input onclick = 'chg()'type="button" /> <script> var x = document.getElementById('hed') function chg() { if (!(x.getAttribute('color', 'green'))){ x.style.color = 'blue'; } else {x.style.color = 'red'} } </script> </body>
31st Dec 2017, 10:41 AM
Lord Krishna
Lord Krishna - avatar
+ 4
This can only be done with inline styling or styling in JS. That's because the code first looks for a JS code and then it starts looking for CSS code. So when the program looked for JS code, it didn't know anything about CSS code and the div element didn't have any style. That's why it always returns false. https://code.sololearn.com/Wlj65d17dBem/?ref=app https://code.sololearn.com/WgU4AoRJZ4lR/?ref=app
31st Dec 2017, 10:44 AM
Tim Thuma
Tim Thuma - avatar
+ 1
thanks so much @Lord Krishna
31st Dec 2017, 11:09 AM
Cole Reizenberg
Cole Reizenberg - avatar
0
when button is pressed it should change the color to blue but the if statement keeps returning false
31st Dec 2017, 10:09 AM
Cole Reizenberg
Cole Reizenberg - avatar
0
@Lord Krishna I liked the get attribute link you gave I used it because it was much cleaner and yet get() still returns null , has() returns false even though I took @Tim Thuma's comment about using inline styling for the browser pls help
1st Jan 2018, 10:08 AM
Cole Reizenberg
Cole Reizenberg - avatar
0
<html> <head> <style> </style> </head> <body> <div style="color:green ;text-align:center" id="hed"> <p> Another sentimental improvisation. </p> <br /> <input type="button" value="Press" onclick="chg()" /> </div> <script> var x = document.getElementById('hed'); var ti = x.getAttribute('text-align'); var y = x.hasAttribute('color') function chg(){ alert(ti); alert(y); } </script> </body> </html>
1st Jan 2018, 10:09 AM
Cole Reizenberg
Cole Reizenberg - avatar