Click here to Skip to main content
15,899,937 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a code pen code. I need to convert the output
var preview = document.getElementById("preview");
to class rather than ID. Can anyone help? Thanks in advance

Codepen Link Here

"use strict";
function dragNdrop(event) {
    var fileName = URL.createObjectURL(event.target.files[0]);
    var preview = document.getElementById("preview");
    var previewImg = document.createElement("img");
    previewImg.setAttribute("src", fileName);
    preview.innerHTML = "";
    preview.appendChild(previewImg);
}
function drag() {
    document.getElementById('uploadFile').parentNode.className = 'draging dragBox';
}
function drop() {
    document.getElementById('uploadFile').parentNode.className = 'dragBox';
}


What I have tried:

<pre>"use strict";
function dragNdrop(event) {
    var fileName = URL.createObjectURL(event.target.files[0]);
    var preview = document.getElementsByClassName("preview");
    var previewImg = document.createElement("img");
    previewImg.setAttribute("src", fileName);
    preview.innerHTML = "";
    preview.appendChild(previewImg);
}
function drag() {
    document.getElementById('uploadFile').parentNode.className = 'draging dragBox';
}
function drop() {
    document.getElementById('uploadFile').parentNode.className = 'dragBox';
}
Posted
Updated 18-Mar-21 23:00pm
v2

1 solution

The clue is in the method name - getElementsByClassName returns multiple elements.

Either take the first element:
JavaScript
var preview = document.getElementsByClassName("preview")[0];
or use querySelector:
JavaScript
var preview = document.querySelector(".preview");
Document.querySelector() - Web APIs | MDN[^]
 
Share this answer
 
Comments
Subir Banik 19-Mar-21 10:08am    
Thanks. I did what you said but the issue is it is only showing a single preview. I need to show the preview of the image two times. Can you please help?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900