DEV Community

Musale Martin
Musale Martin

Posted on

2

Select all nodes in a DOM except the nth query

Say you have a HTML structure like this one:

<body>
    <div>
        <span style="font-weight:bold;">More Lorem Ipsum text: </span>
        <span>And More Lorem Ipsum text</span>
        <span>Some More Lorem Ipsum text</span>
        <span>Get Some More Lorem Ipsum text</span>
        <span>Finally Some More Lorem Ipsum text</span> In conclusion.
    </div>
</body>
Enter fullscreen mode Exit fullscreen mode

I would like to apply some styling to the first span and then I change the remaining spans into text nodes.

The challenge I had was figuring out how to get the rest of the spans after the first. Turns out, it's quite simple:

const spans = document.querySelectorAll("span:not(:nth-child(1))")
spans.forEach(span => {
    const spanTxt = span?.textContent;
    if (spanTxt) span.replaceWith(spanTxt.trim())
})
Enter fullscreen mode Exit fullscreen mode

That JavaScript (TypeScript) code will result to:

<body>
    <div>
        <span style="font-weight:bold;">More Lorem Ipsum text:</span> And More Lorem Ipsum text Some More Lorem Ipsum text Get Some More Lorem Ipsum text Finally Some More Lorem Ipsum text In conclusion.
    </div>
</body>
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay