Get Width with Javascript -


i'm pretty rookie here, gentle. i've poked around here , other places on internet , can't figure out.

  1. i'm trying determine width of div.
  2. i'd in percentage.
  3. i not want use jquery (trying learn javascript as possible)
  4. i'm failing miserably. why won't "thewidth" (below) yield anything?

any appreciated. thanks, dp

html

thewidth = document.getelementbyid("titlebg").style.width;  document.getelementbyid("titlebg").innerhtml = "width = " + thewidth;
#titlebg{    width:50%;    height:50px;   	background-color:#ffcc33;  }
<div id="titlebg">  </div>

you need use element.offsetwidth here

getting percentage going irrelevant - going 50% of current viewport in.

that might not case if have wrapping div or other elements on page may limit width of div, current code that's case.

https://developer.mozilla.org/en-us/docs/web/api/htmlelement/offsetwidth

thewidth = document.getelementbyid("titlebg").offsetwidth;  document.getelementbyid("titlebg").innerhtml = "width = " + thewidth;
#titlebg{    width:50%;    height:50px;   	background-color:#ffcc33;  }
<div id="titlebg">  </div>


Comments