Can I pass the name of a class to a Javascript function?

Coreysan 1,811 Reputation points
2023-01-24T00:17:00.8+00:00

I have a line that calls a javascript function to work with a class, like this:

<a href="#" class="CarryOver" onclick="PerformCalc()"></a>

function PerformCalc() {

   const el = document.getElementById("input1");

   (and do work here)

}

If I know the name of a class in advance, can I pass the classname to the function as a variable?

For example:

<a href="#" class="CarryOver" onclick="PerformCalc(input1)"></a>

function PerformCalc(someclassname) {

   const el = document.getElementById(someclassname);

   (and do work here)

}
Developer technologies ASP.NET ASP.NET Core
0 comments No comments
{count} votes

Accepted answer
  1. Anonymous
    2023-01-24T01:42:44.0433333+00:00

    Hi @Coreysan

    If I know the name of a class in advance, can I pass the classname to the function as a variable?

    Since you are using the getElementById method, the parameter should be the element's id attribute, if you want to transfer the class name, in the function, you should use the getElementsByClassName method.

    To transfer parameter (id or class name) to the JavaScript function, you could refer the following sample:

    <div id="outerElement">
        <input type="text" name="myname1" class="dz_input1" id="input1" />
    
        <a href="#" class="CarryOver" onclick="PerformCalc('input1')">Click Me</a>
    </div>
    
    @section scripts {
        <script> 
            function PerformCalc(id) {
                event.preventDefault(); //prevent the hyperlink default navigate behavior.
                const el = document.getElementById(id); 
                alert(el.value);
            }
        </script>
    }
    

    The result as below:

    User's image


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,

    Dillion

    1 person 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.