Reputation: 419
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.
Upvotes: 0
Views: 5845
Reputation: 419
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;
}
}
Upvotes: 0
Reputation: 2062
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);
}
Upvotes: 3