简体   繁体   中英

How to pass(i mean display) the index value of <li></li>(under <ol></ol> default type) to <p></p> if <p></p> is inside of that said <li></li>?

What I want to achieve here is to display the value of the index of < li >< /li > (under < ol >< /ol > default type) to the < p >< /p >(could be one of more, most likely just one) inside it.

MY INITIAL CODE:

<ol>
    <li>
        <p>First p element in div.</p>
    </li>
    <li>
        <span>Second p</span>
    </li>
    <li>
        <p>A third p element in div.</p>
    </li>
    <li>
        <p>A fourth p element in div.</p>
    </li>
</ol>

SCRIPT:

<script>
    var x = document.getElementsByTagName('li');
    var y = document.getElementsByTagName('p');
    for(var j = 0; j < x.length; j++){
        for(var k = 0; k < y.length; k++) {
            if(x[j].index == y[k].index){
                y[j].innerHTML = j+1;
            }
        }
    }
</script>

OUTPUT:

1.1
2.Second p
3.2
4.3

EXPECTED OUTPUT:

1.1
2.Second p
3.3
4.4

In your code, both x[j].index and y[k].index are undefined. What do you expect to happen when this occurs?

I recommend using querySelectorAll instead of getElementsByTagName - more precise. Then don't get all p elements in the document; just get all p elements in each li . Probably a more elegant way to do this but the nested loop approach works:

 var li = document.querySelectorAll('ol li'); for(var i = 0; i < li.length; i++) { var p = li[i].querySelectorAll('p'); for(var j = 0; j < p.length; j++) { p[j].innerHTML = i + 1; } }
 <ol> <li> <p>First p element in div.</p> </li> <li> <span>Second p</span> </li> <li> <p>A third p element in div.</p> </li> <li> <p>A fourth p element in div.</p> </li> </ol>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM