/    Sign up×
Community /Pin to ProfileBookmark

getting document elements by regular expressions

Hi All,

I need to fetch a document-element but i do not know the full Id of the element.
I only know part of the id of the element. Is it possible to get something like “Give me the element which has id starting with XXXXX”.

Say we have 3 elements
1)<input type=”text” id=”My_name_is_ABC value=”textboxval”>
2)<input type=”text” id=”My_name_is_BEF value=”textboxval”>
3)<input type=”text” id=”My_name_is_YEX value=”textboxval”>

now , in my script i have only “My_name_is_A” and i want to get a reference of an object whose id starts with “My_name_is_A”.
Is it possible to do so ?
Can i use something like
var regularExp = new RegExp(“My_name_is_A”);
document.getElementById(regularExp);

Of course the above does not work ?


——————————————————————————–

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@Orc_ScorcherJun 27.2007 — The (somewhat) hard way: use getElementsByTagName to get a list of all elements in the document, then loop over this list, comparing the elements' id against your regexp.

The toolkit way: take a look at the JS libraries out there, many of them provide a shortcut for this task. For example, with [url=http://jquery.com/]jQuery[/url] you would write [b]$("[@id^=My_name_is_A]")[/b].
Copy linkTweet thisAlerts:
@samanyoluJun 27.2007 — 1)<input type="text" id="My_name_is_ABC[color=red]"[/color] value="textboxval">

2)<input type="text" id="My_name_is_BEF[color=red]"[/color] value="textboxval">

3)<input type="text" id="My_name_is_YEX[color=red]"[/color] value="textboxval">

&lt;body&gt;

1)&lt;input type="text" id="My_name_is_ABC" value="textboxval"&gt;
2)&lt;input type="text" id="My_name_is_BEF" value="textboxval"&gt;
3)&lt;input type="text" id="My_name_is_YEX" value="textboxval"&gt;
4)&lt;input type="text" id="My_name_is_ADC" value="textboxval"&gt;


&lt;script type="text/javascript"&gt;
var el = document.getElementsByTagName('*');

// alert(el.length)

var regularExp = new RegExp("My_name_is_A");
for(var i = 0; i&lt;el.length; i++) {

//alert(el[i].id);

if(el[i].id.match(regularExp)){ el[i].value ="aaa"
}
}
&lt;/script&gt;
×

Success!

Help @MiniMini spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...