简体   繁体   中英

How to get width of dynamic added elements with JavaScript

I want to make horizontally scrollable container which will keep child elements on the y-line (width more that 100% of the screen).

If the data was fixed I would calculate it before rendering and setup the width of the container. The problem is that my data is dynamic, I don't know the number of the child elements that will be added and their width. So I decided to add them dynamic to the container DOM as a children, but when I try to get their width after appending, the result is 0. What I am doing wrong, or if you have a better idea how to do that I will be glad to see your way.

This is what I am doing now:

GalleryContainer.prototype.addItem = function(newItem) {
    var newItemDiv = document.createElement('div');
    newItemDiv.className = 'thumbnail';

    content = document.createElement('img');
    content.setAttribute('src', newItem);

    newItemDiv.appendChild(content);
    this.galleryDiv.appendChild(newItemDiv);
    this.galleryArray.push(newItemDiv);

        // width, offsetWidth, all properties are 0
        console.log(newItemDiv.style.offsetWidth); 
        console.log($(content).css('width'));
        console.log($(newItemDiv).innerWidth());

}

EDIT: I made a jsfiddle example with my problem and in the demo the width is not 0, it's the actual size that i need, so I have to look deeper for the problem. http://jsfiddle.net/valkirilov/QaHn7/1/

bellow code is working, maybe your newItemDiv is not append into HTML Document:

var newItemDiv = document.createElement('div');
newItemDiv.className = 'thumbnail';
$('body').append(newItemDiv);


// width, offsetWidth, all properties are 0
console.log(newItemDiv.style.offsetWidth); 
console.log($(content).css('width'));
console.log($(newItemDiv).innerWidth());

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