0

How do I get the class name through JavaScript using element name from classic HTML.

Like:

<input name="xxx" class="CheckBox" onchange="CheckOnChange()"
       type="CHECKBOX" checked="" value="Y">

I want to check the fields which has the class name "Checkbox" .

How can I solve this? Please help me.

6
  • 4
    Possible duplicate of stackoverflow.com/questions/3808808/… Commented Aug 24, 2016 at 5:11
  • What class name are you trying to import? Post your code and explain a bit more so that we could help better. Commented Aug 24, 2016 at 5:12
  • I would use jQuery('.classname') for that purpose. Commented Aug 24, 2016 at 5:12
  • "How do I get the class name...using element name...? I want to check the fields which has the class name "Checkbox"." - These two requirements seem to contradict each other. Also, if you are trying to do this with JS, why the C# and vb.net tags? Commented Aug 24, 2016 at 5:37
  • @nnnn i am using vb.net the call the JS Commented Aug 24, 2016 at 5:40

2 Answers 2

3

There are a lot of solutions. First to access element classname you use this code :

element.className

Next if you want to test if a classname exist inside the element list, you can test it with indexOf but you could have false positive. class "foo" is not present in the following element.className : "foobar foobuzz"

Best way is to use RegExp :

checkIfElementHasClassName(element, className) {
   return (new RegExp('^|\\s' + className + '\\s|$')).test(element.className);
}
Sign up to request clarification or add additional context in comments.

Comments

0

I just reversed my question to get the required output. Here by reading the class name,I am getting the element name using the below JS:

     var elementName = "";
        var dd = document.getElementsByClassName("CheckBox");
        for (i = 0; i <= dd.length - 1; i++) {
            if (elementName == "")
            { elementName = dd[i].name; }
            else
            {
                elementName = elementName + "," + dd[i].name;
            }
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.