简体   繁体   中英

Javascript change width of div onclick

I'm trying to do three things onclick :

  1. have element with id="notes_content" change display:none to display: block
  2. have element with id="oct" change width = "1190px" to width = "550px"
  3. have elements with class="oct_days" change width = "168px" to width = "73px"

Fiddle of full code: http://jsfiddle.net/ascottz/jX3wh/

The first two happen, but the third does not. I suspect it is a syntax error, but can't catch it myself.

getElementsByClassName returns an array of dom elements, it is not a single instance. You must loop over the array and style each element.

Have a look at the updated fiddle.

for( var i = 0; i < days.length; i++ ){
    days[i].style.width = "73px";        
}

http://jsfiddle.net/jX3wh/4/

document.getElementsByClassName returns somewhat an array of elements, so you cannot simply refer to it as a DOM element in hope that it will work as you refer to each element of the collection (that is possible in jQuery, btw), so you have to use the foreach loop (doesn't matter how are you gonna achieve this -- via simple for() , or for(x in y) , or any other way).

I usually use Array.forEach function, but the specific type of an array returned by the document.getElementsByClassName does not have such function in prototype, so you have to use [].forEach.call(inWhat,function(what){}) syntax, or fallback to for(...) syntax.

Check out this: http://jsfiddle.net/jX3wh/1/ Dunno if it works.

Also, what the f is this???

<div onclick="javascript:showDiv();" class="oct_days">

I am really very surprised this works. You should use onclick="showDiv()" instead, I think.

Somebody, please, tell me how does it work!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM