Get elements by class name in javascript
To get elements using class name we use getElementsByClassName method available
with document object. This method
takes name of class an argument.
It returns array of elements because more than one element(s) can have same class.
It returns array of elements because more than one element(s) can have same class.
<input type="button" value="Get By Class" onclick="GetByClassName()" />
<div id="myDiv" class="myClass">
This is a div
</div>
<script type="text/javascript">
var elements = document.getElementsByClassName("myClass");
if (elements.length > 0) {
alert(elements[0].innerHTML);
}
else
alert("No matching element found");
}
</script>
Comments
Post a Comment