Jump to content

.getElementById(test1), .getElementById(test2) , collect with length?


sonicred

Recommended Posts

Not really - in this situation you could use a for loop to select each one iteratively, though. Alternatively, you could try to select them through some other identifier, such as a common parent or classname.

for (i = 1; i <= 3; i++) {	doSomethingWith(document.getElementById("test" + i));}

Link to comment
Share on other sites

A trick that some programmers use is to create a function to make it more concise.
function $ (id) {return document.getElementById(id);}$('test1');$('test2');$('test3');

wouldn't you want to assign the return to something though? i.e.
function $ (id) {  return document.getElementById(id);}var test1 = $('test1');var test2 = $('test2');var test3 = $('test3');

Link to comment
Share on other sites

While we're on the subject of document.getElementById (and since it is a quiet afternoon) I'd like to remind everyone and explain to noobies not to overuse this method, or any other method that returns references to objects. The goal here is efficiency, and it applies to efficient looking code and code that runs efficiently.The rule is this. If, in a single function, you need to reference the same object more than once, get a reference to it one time only and store it in a local variable. Here's an example of the sort of thing I mean:

document.getElementById("my_element").type = "text";document.getElementById("my_element").value = "Hello";document.getElementById("my_element").style.color = "#ffa";

Not only is this ugly to look at, and hard to read -- it consumes a lot of processor time. If you were building a complicated document with hundreds of elements, and you kept this up, eventually your user would notice some lag time, parts of the page would flicker and jump, etc. AND you would add to the problem significantly if you wrote it this way instead:

$("my_element").type = "text";$("my_element").value = "Hello";$("my_element").style.color = "#ffa";

because now you're calling two functions instead of one, and if you had to iterate that 100's of times . . . (I'm not saying the $ dollar function has no place. I'm warning against overusing it in processor-heavy routines.)A better approach is this,

var el = document.getElementById("my_element");el.type = "text";el.value = "Hello";el.style.color = "#ffa";

As I said, much easier to read, debug, and maintain, and because the reference to "my_element" is generated only once, faster to execute.Again, this is only relevant when you're dealing with processor-heavy loads. Think that will never happen to you? Try to animate something across the screen. You'll see how just a little bit of processor time makes the difference between smooth and herky-jerky.OTOH, writing code this way is a very easy habit to get into, and it's never wrong. It has the added bonus of cutting down on your typing. :)

Link to comment
Share on other sites

Me too. When I first saw it used, I thought THIS IS GREAT! Then I used it on one of these big build-the-whole-freaking-DOM-on-the-fly kind of projects, and performance got terrible. Finally I headslapped myself. "You're calling the same danged function 1000 times more than you need to!"The good news is that my code completion suggests "document" first when I type "d" and "getElementById" is first when I type "g" -- so getting it out there is really not a big deal. I type it out on this forum more than anywhere else. :)

Link to comment
Share on other sites

A better approach is this,
var el = document.getElementById("my_element");el.type = "text";el.value = "Hello";el.style.color = "#ffa";

As I said, much easier to read, debug, and maintain, and because the reference to "my_element" is generated only once, faster to execute.

especially if you change "my_element" to "my_other_element", you only have to change the reference once in the JS.
Link to comment
Share on other sites

wouldn't you want to assign the return to something though? i.e.
I was comparing it to the original code the OP had posted to show how much conciser it is.
$('test1');$('test2');$('test3');.getElementById(test1);.getElementById(test2);.getElementById(test3);

Link to comment
Share on other sites

A better approach is this,
var el = document.getElementById("my_element");el.type = "text";el.value = "Hello";el.style.color = "#ffa";

The code that the OP posted referenced 3 different elements. Otherwise, yes, this would doubtlessly be a better method.
Link to comment
Share on other sites

If you re-read my post carefully, Fmdpa, you'll see it was not meant to improve on or criticize your suggestion. It's just additional information. You might notice this spot in particular:

I'm not saying the $ dollar function has no place. I'm warning against overusing it in processor-heavy routines.
When I think someone has handed out bad advice, I say so in just those words, and there is no ambiguity. :)
Link to comment
Share on other sites

Not really - in this situation you could use a for loop to select each one iteratively, though. Alternatively, you could try to select them through some other identifier, such as a common parent or classname.
for (i = 1; i <= 3; i++) {	doSomethingWith(document.getElementById("test" + i));}

hithat's the way i have now.. but i have to change very time the length.. if i add a row..maybe a other idea?gr.
Link to comment
Share on other sites

Replace 3 with a variable. The value of the variable will be determined by the number of rows. I can't tell you how to determine the number of rows because you have not shown the structure of your HTML. It is probably an easy thing to do.

Link to comment
Share on other sites

@ all other pplthx i did read it but didn't understand.. so i post my function. it's better i gues..but if i'm right it's not possible the obtain .length id=test* *=nummer..isn't there a wildcard % or something?because i need test%.length. with out entering a length my self..gr.

function disDivBlock(param){	var paramnme = param.toString();	var index1 = document.getElementsByName('form[selectection]').length;				var index2 = document.getElementsByName('form[selectection]').length;				var nod1;		for(i=index1;i!=0;i--)	{		if(document.getElementById('selectection'+i.toString()).checked)		{			for(x=index2;x!=0;x--)			{				nod1 = document.getElementById(parmname + x.toString());				if(i == x)				{				 nod1.style.visibility = 'visible';				 nod1.style.width = '';				 nod1.style.height= '';				}				else				{				 nod1.style.visibility = 'hidden';				 nod1.style.width = '0em';				 nod1.style.height= '0em';				}			}		}	}}

Link to comment
Share on other sites

@ all other pplthx i did read it but didn't understand.. so i post my function. it's better i gues..but if i'm right it's not possible the obtain .length id=test* *=nummer..isn't there a wildcard % or something?because i need test%.length. with out entering a length my self..gr.
function disDivBlock(param){	var paramnme = param.toString();	var index1 = document.getElementsByName('form[selectection]').length;				var index2 = document.getElementsByName('form[selectection]').length;				var nod1;		for(i=index1;i!=0;i--)	{		if(document.getElementById('selectection'+i.toString()).checked)		{			for(x=index2;x!=0;x--)			{				nod1 = document.getElementById(parmname + x.toString());				if(i == x)				{				 nod1.style.visibility = 'visible';				 nod1.style.width = '';				 nod1.style.height= '';				}				else				{				 nod1.style.visibility = 'hidden';				 nod1.style.width = '0em';				 nod1.style.height= '0em';				}			}		}	}}

if you read DD's last post, he suggested you show us the HTML so we could have a better idea of how to make 'length' a variable.
Link to comment
Share on other sites

A $ sign is used at the beginning of each JS statement. It alerts the jQuery "interpreter" that this statement will include jQuery. I should dissect the framework someday, and figure out how they create the CSS-style selectors.

Link to comment
Share on other sites

Err, $ is just a function name, that jQuery defines, that allows for the selection of elements in the DOM in various ways. Nothing to do with special interpreters or namespaces or anything (although alright jQuery also does define several properties on $ that can be accessed).

Link to comment
Share on other sites

It boggles my mind how jQuery maintains efficiency.
It's the same situation as with getElementById() that DD pointed out. This:var $tmp = $('.elClass');$tmp.something();$tmp.somethingElse();is going to be more efficient than this:$('.elClass').something();$('.elClass').somethingElse();jQuery's selector function is just incredibly optimized to make the selection process as fast as possible. And like DD also stated, for small applications you won't notice the difference, but when you start using $('.elClass') hundreds or (possibly) thousands of times you'll notice a decrease in performance. Especially with class and tag selectors that return arrays of elements.So, back to the original topic:To reiterate what DD and scientist said, we'll need to see the HTML structure. Then we can help you figure out how to create a 'length' variable to use in your for loop.
Link to comment
Share on other sites

Clearly it can be used inefficiently. Like any tool, it's up to the developer to understand its strengths and weaknesses. Kind of like debating the advantage of ++i over i++ ; 10,000 iteration may reveal a difference. But how often does a script need 10,000 iterations?Some operations really are processor intensive. Tracking mouse movements is notorious for that. If you're building a process that executes once per pixel as the user mouses around the window, you'll want to be very careful about the ultimate number of statements in the process, and that means understanding jQuery's internal structure pretty well. If you just want a click handler, a millisecond's inefficiency is probably not a big deal.EDIT. I should type faster. :)

Link to comment
Share on other sites

offtopicdebating the advantage of ++i over i++ ... i-- is always faster/offtopichtml output..this is just one table.. have more but it's the same...

			<div style="visibility: visible; width: 100%; opacity: 1;" id="tabelblk0" class="tableBlhidden"> 				<table border="0">					<tbody><tr id="ca1.1" class="form-block form-block-check23">						<td>€ xxxx</td>						<td><input name="form[check23][]" value="xxxx" id="check230" type="checkbox"><label for="check230">xxxxxxxxx</label><div class="formClr"></div><span id="component3806" class="formNoError">Invalid Input</span></td>						<td></td>					</tr>					<tr id="ca1.2" class="form-block form-block-check3">						<td>€ xx</td>						<td><input name="form[check3][]" value="xxxxx" id="check30" type="checkbox"><label for="check30">xxxxxxxxxxx</label><div class="formClr"></div><span id="component3087" class="formNoError">Invalid Input</span></td>						<td></td>					</tr>					<tr id="ca1.3" class="form-block form-block-check4">						<td>€ xxxx</td>						<td><input name="form[check4][]" value="xxx" id="check40" type="checkbox"><label for="check40">xxxxxx</label><div class="formClr"></div><span id="component3905" class="formNoError">Invalid Input</span></td>						<td></td>					</tr>					<tr id="ca1.4" class="form-block form-block-check5">						<td>€ xxxx</td>						<td><input name="form[check5][]" value="xxxx" id="check50" type="checkbox"><label for="check50">xxxxxxx</label><div class="formClr"></div><span id="component3903" class="formNoError">Invalid Input</span></td>						<td></td>					</tr>					<tr id="ca1.5" class="form-block form-block-check11">						<td>€  xxx</td>						<td><input name="form[check11][]" value="xxxx" id="check110" type="checkbox"><label for="check110">xxx</label><div class="formClr"></div><span id="component3091" class="formNoError">Invalid Input</span></td>						<td></td>					</tr>					<tr id="ca1.7" class="form-block form-block-check8">						<td>€  xxx</td>						<td><input name="form[check8][]" value="xxxx" id="check80" type="checkbox"><label for="check80">xxx</label><div class="formClr"></div><span id="component3088" class="formNoError">Invalid Input</span></td>						<td></td>					</tr>				</tbody></table>			</div>

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...