jquery - Printing element width in javascript -
i'm trying retrieve html element width in javascript. nothing appears on screen(plain text works, suppose there's wrong syntax). doing wrong? thanks
<head> <script type="text/javascript"> var width = $("#menu").width(); document.write(width); </script> </head> <body> <h1> example </h1> <ul id = "menu"> <li><img src="img/logo.jpg"/></li> <li><a href ="#">home</a> <ul class = "sub1"> <li><a href ="#">news</a></li> </ul> </li> <li><a href ="#">machines</a> <ul class = "sub1"> <li><a href ="#">type1</a></li> <li><a href ="#">type2</a></li> <li><a href ="#">type3</a></li> </ul> </li> <li><a href ="#">mission</a></li> <li><a href ="#">contacts</a></li> </ul> <div id "main"> <h2> whatever </h2> </div> </body>
you're computing , printing width when element doesn't yet exist.
you can :
<div id=head></div> <script type="text/javascript"> $(function(){ // called when dom ready var width = $("#menu").width(); $('#head').html(width); }); </script> as saw, used div instead of head, because setting content of head width doesn't make sense. if want change title of page, use
document.title = width; as noticed j08691, use jquery don't seem import it. if code show real header, need add in head element :
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Comments
Post a Comment