Home > Net >  document.querySelectorAll() only parent items
document.querySelectorAll() only parent items

Time:11-25

I have a simple question, I don't know much about JavaScript, how can I get the following documentation as I want

<ul id='mainul'>
    <li data-uid='1'>1. item</li>
    <li data-uid='2'>2. item
        
        <ul> 
            
            <li data-uid="3">
                3. item
            
                <ul>
                    <li></li>
                </ul>
            
            </li>

        </ul>

        <ul>
            <li data-uid="4">
                4.item

                <ul>
                    <li data-uid="5">5.item</li>
                </ul>

            </li>
        </ul>
    
    </li>
</ul>

I only need to get the 2 ul elements in the #mainul one.

CodePudding user response:

You can use normal scss selecteors to get the node list of thte lis

const listItems = document.querySeectorAll('#mainul > li');

const listItems = document.querySelectorAll('#mainul > li');

console.log(listItems)
<ul id='mainul'>
    <li data-uid='1'>1. item</li>
    <li data-uid='2'>2. item  
        <ul> 
            <li data-uid="3">
                3. item
                <ul>
                    <li></li>
                </ul>
            </li>
        </ul>
        <ul>
            <li data-uid="4">
                4.item
                <ul>
                    <li data-uid="5">5.item</li>
                </ul>
            </li>
        </ul>
    
    </li>
</ul>

  • Related