Tanisha Tanisha - 5 months ago 10
Javascript Question

How to get class list of a tag inside a div on click of div not the tag?

I have 2 divs contains a tag as well as I tag as follows.i am using a on click function that doesn't indicate you have to write the function using it, use can use something like on click of this item get elements and in those elements find certain class where it is placed.

<div class="div" onclick="getclassofitag()">
<a class="atag"></a>
<i class="itag1 itag2"></i>
</div>
<div onclick="getclassofitag()">
<a class="atag"></a>
<i class="itag11 itag22"></i>
</div>


I need to get class list of tag inside the div I clicked.
in cshtml you can use foreach for looping the div, in that case divs repeated will be having same id, same class name. so how i will be able to get the element only i clicked?
How to do it by using pure JavaScript?

the code i really have is

@foreach (var j in footerPage.StaticPageFiles)
{
if (j.Type != "video")
{
<div class="col-sm-4 files">
<i class="fa fa-file " aria-hidden="true"></i><a href="@j.FilePath">@j.FileName</a>
</div>
}

}


it will show a div with height 50px and width 100% and color red. on click of each div i want to apply some class for only the div which i clicked.

Answer

Using classList property will give you the list of classes in the tag:

<div class="div" onclick="getclassofitag(this)">Test1
  <a class="atag"></a>
  <i class="itag1 itag2"></i>
</div>
<div onclick="getclassofitag(this)">Test2
  <a class="atag"></a>
  <i class="itag11 itag22"></i>
</div>

<script type="text/javascript"> 
function getclassofitag(element) {
    aTags = element.getElementsByTagName("a");
    aTagsClass = [];
    for(var i=0; i<aTags.length; i++) {
        for(var j=0; j<aTags[i].classList.length; j++) {
            aTagsClass.push(aTags[i].classList[j]);
        }
    }


    iTags = element.getElementsByTagName("i");
    iTagsClass = [];
    for(var i=0; i<iTags.length; i++) {
        for(var j=0; j<iTags[i].classList.length; j++) {
            iTagsClass.push(iTags[i].classList[j]);
        }
    }
    //This will give you the array of classes in `a` tag and `i` tag
    console.dir(aTagsClass);
    console.dir(iTagsClass);
}
</script>
Comments