document.createElement("img")
how can I set a class to the img element in js?
document.createElement("img")
how can I set a class to the img element in js?
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";
}
save the element as a variable
let element = document.createElement('img');
and then:
element.className = 'someClaasName';
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;
}