...

View Full Version : getElementbyId targetting div



rf9
06-16-2008, 11:55 AM
Hello, first post here and also fairly new to javascript so please excuse any lameness. I'm using my Actionscript knowledge as the basis for my javascript, they seem pretty similar.

I'm trying to select a div that has been generated by javascript. I'm not sure where I'm going wrong. I have 5 divs named title0, title1 and so on and I want to target one using the variable i.

The last line does not work, it returns null or no properties, maybe my syntax is wrong. I kinda made it up :)

var i = 0;
var setProperties = function() {
alert(i); // this works
var userInput = document.getElementById('element_label').value;
document.getElementById('title' + [i]).innerHTML = userInput;
}
If I change the last line to this then the targetting works:

document.getElementById('title' + 1).innerHTML = userInput;

Any advice much appreciated.

abduraooft
06-16-2008, 12:17 PM
try
for(var i=0;i<5;i++)
document.getElementById('title'+i).innerHTML = 'somtext'+i;

rf9
06-16-2008, 12:55 PM
thanks abduraooft,
The code you posted does work the only problem is it changes the text for all 5 divs. My fault as I didn't really give enough explanation in my first post.

I only want to change the text for one div at a time so if 'i' is 3 then the text for title3 will be updated and so on.

Thanks

edit: just noticed an error in my first post ('title' = [i]) should read ('title' + [i]). Original post now corrected.

abduraooft
06-16-2008, 02:10 PM
var i = 0;
var setProperties = function() {
alert(i); // this works
var userInput = document.getElementById('element_label').value;
document.getElementById('title' + [i]).innerHTML = userInput;
}
It should be

document.getElementById('title' +i).innerHTML = userInput;

Kor
06-16-2008, 02:13 PM
Which is the event and when should that function be triggered? Can you post the HTML code as well?

rf9
06-18-2008, 01:35 PM
Thanks for the replies, I figured out a solution now so I thought I'd post it.


//Set value to pass to setProperties function
var showControlPanel = function(count) {
document.getElementById('element_label').setAttribute('onKeyup', 'setProperties('+count+')');
}



// count used for increment
var setProperties = function(count) {
var userInput = $('element_label').value;
document.getElementById('title'+count).innerHTML = userInput;
}
Thanks



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum