Adding img to js

I am using javascript to create an image element like this:

var img = document.createElement('img'); 

      

What would I do to give this img 100% width?

+2


a source to share


2 answers


....

var img = document.createElement('img'); 
img.setAttribute('width', '100%');

      



Make sure you attach img

to body

.

document.getElementsByTagName('body')[0].appendChild(img);

      

+5


a source


You can specify the width on this image: (taken from others answer)

var img = document.createElement('img'); 
img.setAttribute('width', '100%');
document.getElementsByTagName("body")[0].appendChild(img);

      

Or provide a class name and specify it in CSS:

JavaScript:



var img = document.createElement('img'); 
img.setAttribute('class', 'wide');
document.getElementsByTagName("body")[0].appendChild(img);

      

CSS

img.wide {
    width:100%;
}

      

+3


a source







All Articles