DEV Community

Musale Martin
Musale Martin

Posted on

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

Top comments (0)