2

I'm using javascript to create an image element like so:

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

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

1
  • 2
    Bonus points for not using jQuery Commented Apr 30, 2010 at 17:23

2 Answers 2

5

....

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

Make sure that you attach the img to the body.

document.getElementsByTagName('body')[0].appendChild(img);
Sign up to request clarification or add additional context in comments.

Comments

3

You could either specify the width on that image: (taken from others' answer)

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

Or specify a class name and target it in CSS:

JavaScript:

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

CSS:

img.wide {
    width:100%;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.