How do I change HTML objects with my JS strings ?

H

H

Ok, heres the deal ;

I have my script code like this

var v = "place";
for (var i = 0 ; i < 5 ; i++)
{
v = v + i; // or v = "place" +i;
// Here I want to access the resource in the HTML doc, whos id="place1",
id="place2", etc etc, so how can I do that ?
// like "theValueInv".innerText = "bla bla bla bla"; if the resource
with id="place1" is for ewxample a <p>
}


I hope you clever guys can help this newbie with this ...
TIA
H
 
L

Lasse Reichstein Nielsen

H said:
Ok, heres the deal ;

I have my script code like this

var v = "place";
for (var i = 0 ; i < 5 ; i++)
{
v = v + i; // or v = "place" +i;

You want 'v = "place" +i;'. What you have here will give you "place1",
"place12", "place123", etc.
// Here I want to access the resource in the HTML doc, whos id="place1",
id="place2", etc etc, so how can I do that ?

var elem = document.getElementById(v);
// like "theValueInv".innerText = "bla bla bla bla"; if the resource
with id="place1" is for ewxample a <p>

You can use innerText, but that only works in IE and Opera 7. Or you
could use DOM methods that works in all modern browsers (for IE, here
that means IE 5+)

// clear old content
while(elem.hasChildNodes()) {
elem.removeChild(elem.lastChild);
}
// add new
elem.appendChild(document.createTextNode("bla bla bla bla"));

/L
 
R

Richard Cornford

H said:
var v = "place";
for (var i = 0 ; i < 5 ; i++)
{
v = v + i; // or v = "place" +i;
// Here I want to access the resource in the HTML doc, whos
//id="place1", id="place2", etc etc, so how can I do that ?
// like "theValueInv".innerText = "bla bla bla bla"; if the
//resource with id="place1" is for ewxample a <p>
}

Look at:-

<URL: http://www.jibbering.com/faq/#FAQ4_39 >

-and the linked resource.

But if your interest is on locating elements within a document that have
a specific (and unique, as required) ID then the document.getElementById
function is probably the best option:-

function getEl(id){
if(document.getElementById){ //all DOM browsers
return document.getElementById(id);
}else if(document.all){ //IE 4 fall-back
return document.all[id];
}else if(document.layers){ //Netscape 4
return document.layers[id];//but that will only find positioned
//elements on Netscape 4.
}
return null; //no suitable method exists on this browser.
}

....
var el, v = "place";
for(var c = 0;c < 5;c++){
el = getEl(v+c);
if(el){ //so only if the returned value was non-null.
... //do something with the element.
}
}
....

Richard.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top