How does native JS get the number of child elements that the current element belongs to the parent element

2020-10-28 08:18:03 | Web Design | 1k+ Reads

Native JavaScript(Basic)

var child= this;
i = 0;
while ((child=child.previousSibling) != null) {
    i++;
}  


I will tell you where this thing is applied.

Basically every mobile game will have a star system. Especially those card games. 

I want to show you an example of Princess Connect: Re Dive.

You know, if you have played this game, the number of stars of the character is very important.

Someone even made a website dedicated to recording the number of stars for each character.

Of course, not only the number of stars, but also various other information, I will not expand it here.

Today, I will try to show you how to choose the number of stars.

Demo:

Code:

<div>
<span class="star_ctn"><img src="/upload/images/star.png" onclick="ChangeStars()" style="filter:unset;"></span>
<span class="star_ctn"><img src="/upload/images/star.png" onclick="ChangeStars()" style="filter:unset;"></span>
<span class="star_ctn"><img src="/upload/images/star.png" onclick="ChangeStars()" style="filter:unset;"></span>
<span class="star_ctn"><img src="/upload/images/star.png" onclick="ChangeStars()" style="filter:unset;"></span>
<span class="star_ctn"><img src="/upload/images/star.png" onclick="ChangeStars()" style="filter:unset;"></span>
</div>
<script>
    function ChangeStars() {
        var e = window.event;
        obj = e.target || e.srcElement;//get the div
        var starCode = obj.parentNode.parentNode;//get the span
        var starSpan = obj.parentNode;
        i = 0;
        j = 4;
        while ((starSpan = starSpan.previousSibling) != null) {i++;j--;} 
        starSpan = obj.parentNode;       
		starCode.innerHTML="";
        for (a=0;a<i+1;a++) {        
                starCode.innerHTML += "<span class=\"star_ctn\"><img src=\"/upload/images/star.png\" onclick=\"ChangeStars()\" style=\"filter:unset;\"></span><span class=\"star_ctn\">";
        }
        for (a=0; a<j; a++) {
            starCode.innerHTML += "<span class=\"star_ctn\"><img src=\"/upload/images/star_disabled.png\" onclick=\"ChangeStars()\" style=\"filter:unset;\"></span><span class=\"star_ctn\">";
        }
        for (a = 0; a < starCode.childElementCount; a++) {
            if (starCode.children[a].innerHTML == "") {
                starCode.removeChild(starCode.children[a]);
            }
        }
    }
</script>

 

This article was last edited at 2020-10-28 08:39:41