Home > Back-end >  querySelector of item by a pattern of id
querySelector of item by a pattern of id

Time:07-16

I'm trying to get all elements with id feed_item_{n} where {n} can be any integer greater than 0.
I know that I can use document.querySelectorAll('[id^="feed_item_"]') but that doesn't really help because I get also elements with these ids: feed_item_0_x, feed_item_x_0 where x may be any string
Is there a quick way to achieve that in one single line rather than running over all the elements I got from previous command and filttering them?

CodePudding user response:

Since it's not possible to use RegEx within attribute selectors, the only way is to filter your querySelectorAll result; and there.. you can use a regex to match only numbers after feed_item_

It will be something like this

let items = [...document.querySelectorAll('[id^="feed_item_"]')].filter(
  (item) => item.id.match(/\d $/)
);

CodePudding user response:

You also can use :not attribute, to get items whose id doesn't have _x by :not([id*="_x"]

const items = document.querySelectorAll('[id^="feed_item_"]:not([id*="_x"])')

console.log([...items])
<div id="feed_item_1">feed_item_1</div>
<div id="feed_item_2">feed_item_2</div>
<div id="feed_item_x_1">feed_item_x_1</div>
<div id="feed_item_1_x">feed_item_1_x</div>

  • Related