Chetan Nellekeri
Chetan Nellekeri

Reputation: 300

JQuery: Find all id in a page matching with the given pattern

I have set of html elements (dynamic elements) out of which one element is a template.. Now I want to find all the id's in the page except template

Ex:

<div id="text[1]"></div>
<div id="text[2]"></div>
<div id="text[XXX]"></div>

Below Jquery function will give me all three elements, but I want div elements with id's test[1] and test[2] and not test[XXX].. How can we use regex here..?

$("div[id^='test']")

Upvotes: 0

Views: 2296

Answers (4)

Chetan Nellekeri
Chetan Nellekeri

Reputation: 300

Thank you everyone for your contributions.. Below code worked for me..

$("div[id^='text']:not([id$='XXX\]'");

Upvotes: 0

charlietfl
charlietfl

Reputation: 171689

Add a not() filter

$("div[id^='text']").not('[id*=XXX]').css('color','red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text[1]">text[1]</div>
<div id="text[2]">text[2]</div>
<div id="text[XXX]">text[XXX]</div>

Upvotes: 2

Harsha Jayamanna
Harsha Jayamanna

Reputation: 2258

This will return all the Divs you need.

$('div')
    .filter(function() {
        return this.id.match('text\\[.\\]');
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="text[1]"></div>
<div id="text[2]"></div>
<div id="text[XXX]"></div>

Upvotes: 0

Shreevardhan
Shreevardhan

Reputation: 12641

You might not need jQuery for that

[].slice.call(document.querySelectorAll('div'))
  .filter(el => el.id.match(/your regex here/))
  .forEach(el => console.log(el.id));
<div id="text[1]"></div>
<div id="text[2]"></div>
<div id="text[XXX]"></div>

Upvotes: 0

Related Questions