/    Sign up×
Community /Pin to ProfileBookmark

getElementById

Hi all,
I have a problem how to get all elements on a document using getElementById

HTML:
<input id=”one” type=”text”>
<div id=”two”></div>
<div id=”three”></div>

Javascript:
var one=document.getElementById(‘one’);
var two=document.getElementById(‘two’);
var three=document.getElementById(‘three’);

If I have many more elements, Those will take much time. I want to use for to get them all. Please help me…. how to use looping to get all elements.

Thanks… ?

to post a comment
JavaScript

5 Comments(s)

Copy linkTweet thisAlerts:
@JPnycNov 30.2005 — Reference them by the various tag names.

var Divs=document.getElementsByTagName('div');

//then you loop through them like this

for(var i=0;i<Divs.length;i++){

Divs[i].[COLOR=Red]whatever you wanna do to em goes here[/COLOR];



}
Copy linkTweet thisAlerts:
@seandyauthorNov 30.2005 — That's ok, but i want to get all elements in a page/body so i can use directly by each id

one.className="bla";

alert(two.value);

etc.

many thanks before.
Copy linkTweet thisAlerts:
@GordNov 30.2005 — Alternatively.Id them alpha-numerically & put them in an array.

HTML:

<input id="t0" type="text">

<div id="t1"></div>

<div id="t2"></div>

javascript:

var myobjects= new Array();

function updatearray(){

for (i=0;i<3;i++){

myobjects[i]=document.GetElementById("t"+i);

}}









<body onload="updatearray()">



Gord
Copy linkTweet thisAlerts:
@JPnycNov 30.2005 — Are we talking about just elements inside a form or every element on the page?
Copy linkTweet thisAlerts:
@KorNov 30.2005 — you may use a wild card to acces all the taged elements. Than you may check whether they have an id or not.
[code=php]
<script type="text/javascript">
onload=function(){
var idEl=[];// the collection of all the elements which have an id
var el = document.getElementsByTagName('*');
for(var i=0;i<el.length;i++){
if(el[i].id!=''){
idEl[idEl.length]=el[i]
}
}
}
</script>
[/code]
×

Success!

Help @seandy 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 5.18,
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: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

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

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...