Ways to specifically locate the initial list items

Need help creating an array of the first li elements but unsure of how to proceed.

Here is the HTML structure:

<div class="nav">
<ul>
    <li>Element 1</li>
    <li>Element 2
        <ul>
            <li>Element 2.1</li>
            <li>Element 2.2</li>
            <li>Element 2.3</li>
            <li>Element 2.4</li>
        </ul>
    </li>
    <li>Element 3</li>
    <li>Element 4
        <ul>
            <li>Element 4.1</li>
            <li>Element 4.2</li>
            <li>Element 4.3</li>
            <li>Element 4.4</li>
        </ul>
    </li>
</ul>

Looking to target the first li elements of the first ul - element 1, element 2, element 3, element 4. Trying to use querySelectorAll but unsure about the correct syntax without nth-child in CSS.

Here's my JS querySelectorAll code so far:

const allVisibleElements = document.querySelectorAll(''); 

Answer №1

To select the li elements that are direct children of the ul element which is a child of the .nav class, you should utilize the child combinator >:

const allVisibleItems = document.querySelectorAll('.nav > ul > li');

Answer №2

document.querySelectorAll allows you to use CSS Selectors, such as .nav > ul > li.

document.querySelectorAll('.nav>ul>li').forEach(e => console.log(e))
<div class="nav">
<ul>
    <li>Element 1</li>
    <li>Element 2
        <ul>
            <li>Element 2.1</li>
            <li>Element 2.2</li>
            <li>Element 2.3</li>
            <li>Element 2.4</li>
        </ul>
    </li>
    <li>Element 3</li>
    <li>Element 4
        <ul>
            <li>Element 4.1</li>
            <li>Element 4.2</li>
            <li>Element 4.3</li>
            <li>Element 4.4</li>
        </ul>
    </li>
</ul>

Answer №3

Give this a shot:

$('.navigation > li:eq(0)').text();

Alternatively

$('.navigation > li:first').text();

Or maybe

$( ".navigation li:nth-child(1)" ).text();

Answer №4

To achieve this, you can target the direct child elements by using the child combinator >:

const allVisibleElements = document.querySelectorAll('.nav > ul > li');
allVisibleElements.forEach(e => e.setAttribute("style", "background-color:yellow"));
ul,li { background-color: #fff }
<div class="nav">
  <ul>
    <li>Element 1</li>
    <li>Element 2
      <ul>
        <li>Element 2.1</li>
        <li>Element 2.2</li>
        <li>Element 2.3</li>
        <li>Element 2.4</li>
      </ul>
    </li>
    <li>Element 3</li>
    <li>Element 4
      <ul>
        <li>Element 4.1</li>
        <li>Element 4.2</li>
        <li>Element 4.3</li>
        <li>Element 4.4</li>
      </ul>
    </li>
  </ul>
</div>

Answer №5

One handy method to retrieve the JS path of a DOM element is to utilize the dev tools section in Google Chrome. Simply right-click on the desired element and select the option to copy its JS path. While there are alternative approaches available, this method is considered to be the most straightforward.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for creating a CSS triangle background on a div without relying on borders or images

I have experience creating triangles using CSS borders and images, but this time I want to achieve it using background color. Here is the image of the desired outcome: https://i.stack.imgur.com/qP3yt.jpg If anyone can assist me with this, it would be gre ...

Callback function triggered upon the creation of a DOM node

I am in search of a way to have a specific callback function run each time a div that matches a particular selector is added to the DOM. I have explored the DOM events documentation and the event closest to what I need seems to be "load", however, it does ...

In order to enhance your programming skills, avoid hard coding functions and ensure that data is returned after binding changes

I am trying to create a method where I can provide a DOM as a parameter and retrieve data from image_preview. The goal is to make image_preview reusable instead of hardcoding it inside the function. Additionally, I want to separate image_preview.model() an ...

Using JavaScript to generate dynamic folders in Alfresco is not functioning as expected

Working with Alfresco 4.0.d community edition (also tested on Alfresco 4.0.c) on an Oracle Linux 64-bit virtual machine using Firefox. I've been developing a script to dynamically create sub-folders as new items are added to a space/folder via a rule ...

Animating SVG while scrolling on a one-page website

Is there a way to incorporate SVG animation scrolling in a single page website? I am inspired by websites like and . The first one stands out to me because the animation is controlled by scrollup and scrolldown actions. I haven't written any of my S ...

Tips for determining if an HTMLElement has already been created

One issue I'm facing is with a third party component that emits an "onCellEdit" event and passes a cell element as a parameter. My goal is to automatically select the entire text in the input element generated inside this cell when the event occurs. ...

Encountering a Basic React Issue: Unable to Implement @material-ui/picker in Next.js

I'm currently attempting to integrate the @material-ui/pickers library into my Next.js application. In order to incorporate the Picker provider, I followed the guidance provided in the Next.js documentation by adding the _app.js file inside /pages: i ...

Guide on displaying gallery images when clicking on a specific class

I am in the process of developing a gallery tab for a website, initially displaying three thumbnails. The goal is to reveal the remaining thumbnails when a class named show-all is clicked. I have successfully animated the gallery's height to show the ...

Sticky positioning is not maintaining its position at the top

I've noticed a strange behavior where, when I scroll down, the yellow box goes on top of the blue box. I have set both boxes to have a position sticky so that they should stay in place and not overlap. However, I want only the orange box to be scrolla ...

TypeScript interface with an optional parameter that is treated as a required parameter

Within my interface, I have a property that can be optional. In the constructor, I set default values for this property, which are then overridden by values passed in as the first parameter. If no properties are set, the defaults are used. I am looking fo ...

What is the best method to retrieve the nested value in this JavaScript/HTML code?

Can anyone help me extract the value "Yes, I am a Speaker" from this code using Javascript DOM element with getElementById? The challenge is that the value is nested inside a list element without any specific attributes. Each block of code has a unique l ...

How can I adjust height without affecting weight in CSS using curly brackets?

Can CSS be used to specifically adjust the height of a curly bracket without changing its thickness? I have been attempting to modify the height of a curly bracket dynamically by adjusting the font-size, but this also alters the weight. Is there a workar ...

A guide on extracting the geometry from an STL model imported into three.js

After using STLLoader to load an STL file into three.js, I am trying to access the vertices and geometry of the model for further use. However, I am encountering difficulty in retrieving the geometry after calling the loader. How can I achieve this? Belo ...

Oops! There seems to be a problem with inserting an image using

I am trying to insert multiple images with a loop when clicked. The images are named "0.jpg","1.jpg","2.jpg" etc. To achieve this, I am using an array with all the elements: {name: '1', result: 1, prefecture: "city", photo1: "0.jpg"}, and my l ...

Controlling LED lights using Johnny-Five and Arduino in NW.js

I have a setup with my board that includes two buttons (each with pull-up resistors) and two LEDs. My goal is to make each button activate its corresponding LED while deactivating the other one. Here's the code I'm using: var five = require(&ap ...

ng-select search functionality failing to display any matches

Currently, I am encountering an issue with the ng-select functionality in my Angular CLI version 11.2.8 project. Despite using ng-select version 7.3 and ensuring compatibility with the Angular CLI version, the search functionality within the select eleme ...

What is the best way to line up changing column values with changing row values in an HTML table?

In its current state, the data appears as follows without alignment: https://i.sstatic.net/o5OLu.jpg The data columns are housed within a single variable due to the presence of multiple excel tabs with varying columns. Within the tr tag, rows are checked ...

Debugging NodeJs: The occasional success and Async.map troubles

Below is the structure of my config json file. "constraints": { "input": "input", "output": "output" } I want to read this file and generate directories for input and output along with their subdirectories. var fs = require("fs"); var async = ...

Revising text for real-time editing

Most of us are familiar with the functionality on StackOverFlow that allows you to preview your text before posting a question. I'm interested in implementing a similar feature on my website and am looking for some guidance on how to get started. I ...

How to update data in AngularJS grid component using ng-bind directive

As a newcomer to AngularJS, I'm facing an issue that I need help with. Here's my problem: I have an ng-grid connected to a table. Inside the grid, there are values along with an ID (which is a foreign key from another table). Instead of display ...