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.

Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
charu
  • 389
  • 2
  • 4
  • 12
  • 4
    Possible duplicate of http://stackoverflow.com/questions/3808808/how-to-get-element-by-class-in-javascript – Mairaj Ahmad Aug 24 '16 at 05:11
  • What class name are you trying to import? Post your code and explain a bit more so that we could help better. – xCodeZone Aug 24 '16 at 05:12
  • I would use jQuery('.classname') for that purpose. – Rafi Ud Daula Refat Aug 24 '16 at 05: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? – nnnnnn Aug 24 '16 at 05:37
  • @nnnn i am using vb.net the call the JS – charu Aug 24 '16 at 05:40
  • The question wording is unclear. Is your question: "How do I test if an element has a particular class?", or "How do I test if an element with the 'Checkbox' class is checked?", or "How do I set all checkboxes with the 'Checkbox' class to be checked?" Or something else? – nnnnnn Aug 24 '16 at 06:35

2 Answers2

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);
}
Arnaud Gueras
  • 2,014
  • 11
  • 14
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;
            }
        }
charu
  • 389
  • 2
  • 4
  • 12