最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - get total width of children elements - Stack Overflow

programmeradmin6浏览0评论

I have some HTML tags:

<div id="container">
   <input type="text" id="a">
   <textarea id="b"></textarea>
   <div id="c" style="width:200px"></div>
   <div id="d" style="width:20%"></div>
</div> 

#a and #b have no css width attribute. How could I calculate the total width of container's children elements in pixel?

I have some HTML tags:

<div id="container">
   <input type="text" id="a">
   <textarea id="b"></textarea>
   <div id="c" style="width:200px"></div>
   <div id="d" style="width:20%"></div>
</div> 

#a and #b have no css width attribute. How could I calculate the total width of container's children elements in pixel?

Share Improve this question edited May 7, 2014 at 14:56 Lewis asked May 7, 2014 at 14:47 LewisLewis 14.9k14 gold badges70 silver badges88 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 18

Without jQuery, go this way:

var children = document.getElementById('container').children;
var totalWidth = 0;

for (var i = 0; i < children.length; i++) {
    totalWidth += parseInt(children[i].offsetWidth, 10);
}

To check whether you need offsetWidth or something else see
Stackoverflow - Understanding offsetWidth, clientWidth, scrollWidth and -Height, respectively

This code is shorter and use vanilla-js:

const el = document.querySelector('.some-el')
const totalWidth = Object.values(el.childNodes).reduce((total, i) => total + i.offsetWidth, 0)
console.log(totalWidth)

With jQuery, you can do it like this:

var width = 0;

$('#container').children().each(function () {
    width += $(this).outerWidth(); 
    // change to .outerWidth(true) if you want to calculate margin too.
});


console.log(width);

var totalWidth = 0;
document.querySelectorAll('#container > *').forEach(function(child) {
  totalWidth += parseInt(child.offsetWidth, 10);
});

console.log('Total Width: ', totalWidth);
<div id="container">
   <input type="text" id="a">
   <textarea id="b"></textarea>
   <div id="c" style="width:200px"></div>
   <div id="d" style="width:20%"></div>
</div>

发布评论

评论列表(0)

  1. 暂无评论