-1
document.createElement("img")

how can I set a class to the img element in js?

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
non doe
  • 11
  • 2
  • `var elmImg = document.createElement("img"); elmImg.className = 'foo'; – Mister Jojo Feb 05 '21 at 23:59
  • 1
    Does this answer your question? [How can I change an element's class with JavaScript?](https://stackoverflow.com/questions/195951/how-can-i-change-an-elements-class-with-javascript) – SpartaSixZero Feb 06 '21 at 00:02

3 Answers3

0

To add the class to all of the images on your page with jQuery:

$("img").addClass("imagedropshadow")

Without jQuery is is not very difficult either:

var images = document.getElementsByTagName("img");
var i;

for(i = 0; i < images.length; i++) {
    images[i].className += " imagedropshadow";
}
Nilesh Kant
  • 351
  • 2
  • 10
0

save the element as a variable

let element = document.createElement('img');

and then:

element.className = 'someClaasName';
Lukas
  • 36
  • 2
0

To add a class to an element using javascript use .className => el.className = 'listItem'. Here we add the class name listItem to an element.

MDN: The className property of the Element interface gets and sets the value of the class attribute of the specified element.

let img = document.createElement("img");
img.src= 'https://www.imagesource.com/wp-content/uploads/2019/06/Rio.jpg';
img.className = 'myclassname';

document.body.append(img)

console.log(img)
.myclassname {
  width: 10rem;
  height: 10rem;
}
dale landry
  • 7,831
  • 2
  • 16
  • 28