Syntax question when testing an element name in javascript

Coreysan 1,736 Reputation points
2024-04-03T18:46:58.0766667+00:00

I have some lines of Javascript in my view, as follows:

let dropzoneElement1 = document.querySelector((".dz1");

updateThumbnail(dropzoneElement1);

let dropzoneElement2 = document.querySelector((".dz2");

updateThumbnail(dropzoneElement2);

function updateThumbnail(dzElementParm) {

...

}

What is the syntax to test the name in dzElementParm? For example,

if (dzElementParm = "dz1") { do stuff }

else if (dzElementParm = "dz2") { do something different }

Im trying to do different things depending on which dropzoneElement (1 or 2) was passed.

In my test, this line didn't work:

if (dzElementParm = dropzoneElement1) { do stuff }

.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,905 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,597 questions
0 comments No comments
{count} votes

Accepted answer
  1. Michael Taylor 54,731 Reputation points
    2024-04-03T19:06:29.8633333+00:00

    Couple of ways to solve this but since your selector is looking for elements with a specific CSS class then why not just do that inside the function as well.

    function updateThumbnail ( element ) {
       if (element.hasClass("dz1")) {  
       } else {
       }
    }
    

    Of course if the function is going to handle that then really you should just query the DOM once to get all the elements (both dz1 and dz2, preferably using a separate CSS class that is applied to both. Then enumerate the elements and call your helper function on each one.

    Alternatively if you only expect to ever have 1 of each then grab them both and pass them to the same function.

    let dropzoneElement1 = document.querySelector((".dz1");
    let dropzoneElement2 = document.querySelector((".dz2");
    
    updateThumbnail(dropzoneElement1, dropzoneElement2);
    
    function updateThumbnail ( element1, element2 ) {
       //element1 is dz1
       //element2 is dz2
    }
    

    Another approach is to simply pass what you already know as part of the arguments.

    let dropzoneElement1 = document.querySelector((".dz1");
    updateThumbnail(dropzoneElement1, "dz1");
    
    let dropzoneElement2 = document.querySelector((".dz2");
    updateThumbnail(dropzoneElement2, "dz2");
    
    function updateThumbnail ( element1, elementType ) {
       if (elementType === 'dz1') {
       } else if (elementType === 'dz2') {
       }
    }
    
    2 people found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.