206k views
0 votes
Which of the following JavaScript code snippets correctly sets the width attribute of the tag to 125?

A. document.querySelector('img').width = 125;
B. document.getElementsByTagName('img')[0].style.width = '125px';
C. document.getElementById('imgId').width = 125;
D. document.querySelector('#imgId').setAttribute('width', '125');

User Kkudi
by
9.2k points

1 Answer

5 votes

Final answer:

The correct JavaScript code snippet to set the width attribute of the tag to 125 is 'document.querySelector('img').width = 125;'. It directly modifies the DOM element attribute.

Step-by-step explanation:

The JavaScript code snippet that correctly sets the width attribute of the <img> tag to 125 is:

A. document.querySelector('img').width = 125;

This code uses document.querySelector to select the first image element in the document and then directly sets its width property to 125, which denotes 125 pixels. This approach modifies the actual DOM element attribute, not the CSS style.

Option B sets the CSS style and not the DOM attribute. Option C requires an id to be specified and the 'imgId' might not exist. Option D also requires the use of an id and even though it correctly sets the DOM attribute, it is not a guarantee that 'imgId' is the correct identifier for the <img> tag in question.

User Tj Gienger
by
7.1k points