gongpex Posted February 5, 2015 Share Posted February 5, 2015 Hello everyone if using php I can change the value of element like this : <div class="<?php if(x==1) echo tes1; else echo tes2; ?>">some text....</div> Q : but how about in javascript? when I put some tes code like this it won't work : <script type="text/javascript">if(screen.width < 1281) { x = 'r'; } else { x = 'b'; } function disp() { document.write(x);}</script><style type="text/css"> .r {color: red;} .b {color : blue;}</style><body> <div class="javascript:disp()">TES</div></body> this my expectation : when debug on browser it will display: <div class="r">TES</div> when screen less than 1280px and the color of TES is red and <div class="b">TES</div> when screen greater than 1280px and the color of TES is blue please someone help me Thanks Link to comment Share on other sites More sharing options...
Don E Posted February 5, 2015 Share Posted February 5, 2015 Using document.write() creates a new document. One way to do it is give the TES div a id and then in the disp() function using document.getElementById to access the div and then change it's className to x. There are various ways to accomplish what you're doing. Whatever works best for you to understand. Here's a way: <!doctype html><html><head><meta charset="UTF-8"><title>TES</title><script type="text/javascript"> var x; window.onload = function () { if(screen.width < 1281) { x = 'r'; } else { x = 'b'; } disp();}function disp() { document.getElementById('TES').className = x;}</script><style type="text/css"> .r {color: red;} .b {color : blue;}</style></head><body> <div id="TES">TES</div></body></html> Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now