Nick Maddren
Nick Maddren

Reputation: 583

Select Elements Numerically Dynamic in jQuery

I'm just wondering how I can select elements in jQuery dynamically, for example here is a selector of mine:

$("#video_background_video_0, #video_background_video_1, #video_background_video_2, #video_background_video_3, #video_background_video_4").remove();

As you can see this isn't the best example of DRY programming, I'd like to create a selector that selects all elements that begin with #video_background_video_. I basically just want to select the above elements in the cleanest way, I was wondering if there is a way that I can dynamically select these elements with some sort of count instead of placing all of my selectors like so, it just looks very messy and I'm wondering if there is a better way to do this when it comes to elements with a numeric ending?

As jQuery uses a CSS selector syntax I am unsure how I can do this.

Thanks, Nick

Upvotes: 0

Views: 32

Answers (2)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85575

You can use start-with selectors:

$('[id^="video_background_video"]').remove();

There are other attribute selectors you might be interested here.

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

Try to use attribute starts with selector,

$("[id^='video_background_video'")

Also make sure that, this selector is not a native css based one. It will fetch the elements after executing regular expressions internally. So it would be better to use it in a minimum level. Its Better to set a common class to those elements and use class selector instead.

Upvotes: 0

Related Questions