How to find the width of a div using vanilla JavaScript?

前端 未结 8 1276
遥遥无期
遥遥无期 2020-11-27 10:19

How do you find the current width of a

in a cross-browser compatible way without using a library like jQuery?

8条回答
  •  误落风尘
    2020-11-27 11:01

    You can also search the DOM using ClassName. For example:

    document.getElementsByClassName("myDiv")
    

    This will return an array. If there is one particular property you are interested in. For example:

    var divWidth = document.getElementsByClassName("myDiv")[0].clientWidth;
    

    divWidth will now be equal to the the width of the first element in your div array.

提交回复
热议问题