PDA

View Full Version : Get elements by class name



riptide
04-03-2007, 06:08 PM
I wanted to know if you could use this in a switch function

this is the class function

getElementsByClass Written By: Dustin Diaz
http://www.dustindiaz.com/getelementsbyclass/

Slight minor modification by: Jon Christopher
http://www.MondayByNoon.com */

function getElementsByClass(node,searchClass,tag) {
var classElements = new Array();
var els = node.getElementsByTagName(tag); // use "*" for all elements
var elsLen = els.length;
var pattern = new RegExp("\b"+searchClass+"\b");
for (i = 0, j = 0; i < elsLen; i++) {
if ( pattern.test(els[i].className) ) {
classElements[j] = els[i];
j++;
}
}
return classElements;
}


function seasons(){
var myEls = getElementsByClass(document,'tt1', 'a');
for ( i=0;i<myEls.length;i++ ) {
seasonfind=myEls[i];
seasonfind.onclick = function()
{
switch(seasonfind){
case tt1:
document.getElementById("misterioProgram").style.display="block"

break
case tt2:
document.getElementById("misterioProgram").style.display="inline"

break
case tt3:
document.getElementById("misterioProgram").style.display="none"
break
}

}
}
}

I is the right way to use a getElementsByClass function to change the display of a div by the class of the links that were clicked


<a class="tt1" href="#">
<a class="tt2" href="#">
]<a class="tt3" href="#">

riptide
04-04-2007, 03:28 PM
is this to hard to understand.

jscheuer1
04-04-2007, 03:48 PM
Although it is hard to say without a link to your page, I don't think that is the correct way to use it. A proper getElementsByClassName() function would simply return an array of elements with the class attribute in question. Using it has no advantage over getElementById() unless you are trying to get more than one element at a time. To do that, you would need more than one element with a given class. Your example shows three anchor tags, each with a different class name. My advice is to switch to id and use getElementById(). It will save unnecessary complications.

riptide
04-04-2007, 07:43 PM
that's just there to understand it. in the end there will be about ten of each links that will change a div from display none to block.

but I wanted to add another function to the links by onclick


<a class="tt1" href="URL" onclick="program()">
then I was going to use setAttribute("herf", movie.getAttribute("href")
to send Realplayer,Quicktime or WMP the links herf with the help of the
getElementsByClassName() function.

jscheuer1
04-05-2007, 05:06 AM
I think you are confused. The getElementsByClass function doesn't work. That stuff with the \b's as used causes missed class names. Once that is fixed, your function seasons() is so unclear, I have no idea what it is trying to do.

Here is a working version of getElementsByClass function:


function getElementsByClass(node,searchClass,tag) {
var classElements = new Array();
var els = node.getElementsByTagName(tag); // use "*" for all elements
var pattern = new RegExp('\\b'+searchClass+'\\b');
for (var i = 0; i < els.length; i++)
if ( pattern.test(els[i].className) )
classElements[classElements.length] = els[i];
return classElements;
}

riptide
04-06-2007, 04:45 PM
ah, I knew there was something wrong with that Class function.

I'll see if I can do anything with this one then I will ask you something else.

I'm a bit confused about how you can use class functions I mean I know they work like getElementById()

but I wonder if you can use switch to check the class of the links and then do something with the links from each class.

function seasons was going through all the classes then putting them in var seasonfind. Someone on another forum told me to set it up that way.

jscheuer1
04-06-2007, 05:25 PM
The getElementsByClass function will only get you one class at a time and it will be an array of all items with that class name, even if there are no items (returns an empty array) or if there happens to be only one item in that array. There is no way to act upon that data to get elements with other classes. The fundamental difference between getting elements via their class and by their id is that there can only be one element with a given id, at least for scripting purposes and, it is returned as a single object, not as an array.

The getElementsByClass function is very similar to the:

getElementsByName()

and the:

getElementsByTagName()

methods which return a collection of elements as an array or pseudo array (I'm not certain which, it behaves like an array).

Also, do not confuse any of this with javascript classes which are something else entirely and have nothing particular to do wth HTML class names - getElementsByClass is a function written to mimic the functionality of a javascript method like getElementsByName() but keying off of an element's class name.

riptide
04-06-2007, 06:47 PM
no I'm not getting javascript classes and HTML classes confused.

if classElements is a variable in your script it holds the array of class names.

can't I retrieve the class like if I did something like.


if the link with the class 4 was clicked a div would change to display block and if a link with the class 3 was clicked another div would change to display block.

And I wanted to assign this to all links. Without putting onclick in the <A> tag



<a class="4">
<a class="4">
<a class="3">
<a class="3">
<a class="5">
<a class="5">


switch(classElements){
case 4:
document.getElementById("divone").style.display="block"

break
case 3:
document.getElementById("divtwo").style.display="block"

break
case 5:
document.getElementById("divthree").style.display="block"
break


or would it be something like




var thediv

switch(thediv){
case :getElementsByClassName("3"):
document.getElementById("divone").style.display="block"

break
case :getElementsByClassName("4")
document.getElementById("divtwo").style.display="block"

break
case :getElementsByClassName("5")
document.getElementById("divthree").style.display="block"
break

jscheuer1
04-07-2007, 05:38 AM
You will get into trouble sooner or later using numbers as class names. Also, I think you misunderstand the switch() method. You might be better off using if(condition)/else if(condition) statements. But, if you really want to use switch(), at least have a look here:

http://www.hscripts.com/tutorials/javascript/switch-case.php

The bottom line on switch is that you must have something that could have different values here:


switch(. . .)

And then, your case labels are the possible results followed by the desired action for each one. As an example of part of your problem with switch:



switch(classElements)

will never represent the numbers in your case labels, it will always be an array. In your second example, at least with the code shown:



switch(thediv)

will have no value. You also need to close your brace that you open after the switch at the end of the case labels/actions:



switch(classElements){
case 4:
document.getElementById("divone").style.display="block"

break
case 3:
document.getElementById("divtwo").style.display="block"

break
case 5:
document.getElementById("divthree").style.display="block"
break

//needs a closing brace here

riptide
04-10-2007, 03:39 PM
yeah I know I didn't set it up right the first time. I know how to set up switch but with this class function I'm confused. I didn't want to use an if else statement because I think it's going to be too long and I don't need my code to get much larger

I'll have a larger div and depending on what class of links are clicked there will be a smaller div in the larger one. That's how I have my code set up anyway.


var bigDiv=document.getElementById("bigd")
switch(bigDIV)

but will I need to use appendChild if my slammer divs are already positioned over the big div but are on display block, no.

why will my last code have no value?

will I need to set it up like this?

getElementById("bigd").getElementById("divtwo").style.display="block"

jscheuer1
04-11-2007, 04:15 PM
The last code:



var thediv

switch(thediv){
case :getElementsByClassName("3"):
document.getElementById("divone").style.display="block"

break
case :getElementsByClassName("4")
document.getElementById("divtwo").style.display="block"

break
case :getElementsByClassName("5")
document.getElementById("divthree").style.display="block"
break

has no value for thediv, the variable is declared but nothing is assigned to it. It will always be undefined in the switch. So, none of the case statements will execute.

riptide
04-17-2007, 05:47 PM
I understand but in my last post I use
var bigDiv=document.getElementById("bigd")
switch(bigDIV)

will something like this work.

jscheuer1
04-17-2007, 06:17 PM
No, work it out using if statements. That way, hopefully, things will be much clearer to you. Just for your information though, switch() requires that its value (red in the below):


switch(value)

be something that will be different in different cases and the case statements execute depending upon whether or not they match that value.

If you switch a div, as you seem intent upon doing, it will always be an object, the same object. So, there will be no differing values from which the case statements can be tested against.

riptide
04-17-2007, 06:24 PM
ah I understand now. But this would work with an if statement? I really though switch was like if else.

I guess I wasn't understanding how to use it.
okay i'll use if else. But I still don't how to use the class function for this.
:(

jscheuer1
04-17-2007, 06:50 PM
You really are trying to learn two or more things at once then. Switch, and getElementsByClassName, perhaps other methods and/or functions you are working with are unfamiliar to you too.

In a case like that, it is best to individually master the new or unfamiliar items separately before trying to combine them.


More Info:

getElementsByClassName
To understand getElementsByClassName, it would be helpful to have a good understanding of arrays and of the getElementsByTagName and getElementsByName methods that the invented function getElementsByClassName mimics for use with class attributes. You also should have an understanding of how class attributes, unlike names, id's or tag names can be compound - consisting of one or more class name. You should also have a grasp of the fact that getElementsByClassName is not a method like getElementsByName or getElementById but a made up function created to act like a method. As such, it can only do what it is written to do. By contrast, a method always does what it does as long as it is supported by the browser.

I realize that learning all that stuff just to use getElementsByClassName seems like a lot but, it isn't all that much. If you are in a big hurry, you need to at least understand getElementsByTagName and how that differs from getElementById. getElementsByClassName is more like getElementsByTagName (returns an array of objects), than it is like getElementById (returns a single object).

Switch is really never required. In certain situations it can be more efficient than if and if/else branching but, if you don't understand how to use if and if/else for what you are doing, it is unlikely you are ready to use switch for it.

riptide
04-17-2007, 07:13 PM
hum....kay I understand class. I understand if else and I know you are getting more than one element with the class function. but how would you use it with something like this?

var thea = getElementsByTagName(a)

if (thea ==classname){do something}
else if (thea==classname2{do somthing else}

This is really what i'm trying to do

jscheuer1
04-17-2007, 07:48 PM
I think you are missing out on the idea that document.getElementsByTagName('a') is an array. Also, abstract code without either some idea of its placement on the page and the markup involved is meaningless. This might be somewhat like what you are going for:


<a class="linksclass1" href="#">Link Text</a><br>
<a class="linksclass2" href="#">Link Text</a>
<script type="text/javascript">
var cn1='linksclass1', cn2='linksclass2';
var theas = document.getElementsByTagName('a');
for (var i_tem = 0; i_tem < theas.length; i_tem++)
if (theas[i_tem].className==cn1){do something}
else if (theas[i_tem].className==cn2){do something else}
</script>

riptide
04-17-2007, 07:53 PM
yeah that is but I though using the classname function was a short cut to having to store the class names in a var because in the end I'll have like 20 classes.

I though an array would work better.

jscheuer1
04-17-2007, 08:23 PM
All that getElementsByClass can do is retrieve an array of items with a specified class name. So you could do like:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

</head>
<body>
<a class="linksclass1" href="#">Link Text1</a><br>
<a class="linksclass1" href="#">Link Text2</a><br>
<a class="linksclass2" href="#">Link Text3</a><br>
<script type="text/javascript">
function getElementsByClass(node,searchClass,tag) {
var classElements = new Array();
var els = node.getElementsByTagName(tag); // use "*" for all elements
var pattern = new RegExp('\\b'+searchClass+'\\b');
for (var i = 0; i < els.length; i++)
if ( pattern.test(els[i].className) )
classElements[classElements.length] = els[i];
return classElements;
}

function actOnaClass(cn, action){
var theitems=getElementsByClass(document,cn,'a')
for (var i_tem = 0; i_tem < theitems.length; i_tem++)
action(i_tem, theitems)
}
</script>
<input type="button" value="1" onclick="actOnaClass('linksclass1', function(i_tem, theitems){alert(theitems[i_tem].innerHTML)})"><br>
<input type="button" value="2" onclick="actOnaClass('linksclass2', function(){alert('something else')})"><br>
</body>
</html>

But, you would still need to tell it, at some point, what class name you are looking for. Here that info is passed with the onclick function.

riptide
04-17-2007, 08:39 PM
okay I'm fine with everything before
function actOnaClass @_@

so I put an action where is says action and classname where it says cn
(cn, action)

but why put the functions in the input buttons shouldn't it be in the script.

If the links send the info or I already have it listed with if else.


But, you would still need to tell it, at some point, what class name you are looking for. Here that info is passed with the onclick function.


<input type="button" value="1" onclick="actOnaClass('linksclass1', function(i_tem, theitems){alert(theitems[i_tem].innerHTML)})"><br>
<input type="button" value="2" onclick="actOnaClass('linksclass2', function(){alert('something else')})"><br>
</body>
</html>

So if the links that are clicked call the function to check their class and then do something. It looks like I should just us your other code and scrap the classname function.

and If I wan't something else to call the function I could use the get ByClassNames

jscheuer1
04-17-2007, 09:46 PM
Something tells me you want something more like so:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

</head>
<body>
<a class="linksclass1" href="#">Link Text1</a><br>
<a class="linksclass1" href="#">Link Text2</a><br>
<a class="linksclass2" href="#">Link Text3</a><br>
<script type="text/javascript">
var action=new Object();
action.linksclass1=function(e){
var el=window.event&&window.event.srcElement? window.event.srcElement : e&&e.target? e.target : null;
if(el)
alert(el.innerHTML);
return false;
}
action.linksclass2=function(){
alert('something else');
return false;
}
var theas=document.getElementsByTagName('a');
for (var i_tem = 0; i_tem < theas.length; i_tem++)
theas[i_tem].onclick=action[theas[i_tem].className];
</script>
</body>
</html>

riptide
04-18-2007, 06:08 PM
yeah that will work. I thougt javascript couldn't find or even know of class names. I must not understand what javascript can do with class name and what it can't. now I wonder why getElementsByclassName was such a big issue.

so I just keep adding

action.linksclass=function()
and
return false;
for every class.
sounds good enough

jscheuer1
04-18-2007, 06:51 PM
Well, in fairness to the getElementsByClass folks, whoever they may be, my little bit here:


var theas=document.getElementsByTagName('a');
for (var i_tem = 0; i_tem < theas.length; i_tem++)
theas[i_tem].onclick=action[theas[i_tem].className];

is a sort of customized version of that. It requires that the class names have counterparts as properties of the action object and that these properties be functions. It also depends upon using only one class per anchor tag.

Some error checking may be required for situations where you have an anchor with no class name, a compound class name or with one not represented by an action. Something like:


var theas=document.getElementsByTagName('a');
for (var i_tem = 0; i_tem < theas.length; i_tem++)
if(theas[i_tem].className&&theas[i_tem].className.indexOf(' ')<0&&action[theas[i_tem].className])
theas[i_tem].onclick=action[theas[i_tem].className];

riptide
04-18-2007, 07:08 PM
hum....but I don't need it anyway.
cool,by the way I'm really not good with objects so I went for a function. :o

I guess I need to study them more

jscheuer1
04-18-2007, 07:25 PM
Well, that's the difference between writing your own code and using someone else's. If you know a certain error will never come up, you don't have to check for it in your own code.

riptide
04-18-2007, 07:39 PM
true and I never understand how javascript didn't interact with classnames. if I tried to make my own class name function, I somehow would have found out I was confused about their interactions.

riptide
04-21-2007, 05:36 PM
heay I'm confused about your object.

I added

action.linksclass2=function(){
document.getElementById("misterioProgram").style.display="block";
return false;
}
action.linksclass3=function(){
alert('something new');
return false;


and have two links with

<li><a class="linksclass2" href="#" >
the end part one open misterio</a></li>
<li><a class="linksclass3" href="#" onclick="">the classes </a></li>

is the problem that they are in a li tag. becuse when I click on them nothing happends

jscheuer1
04-21-2007, 07:26 PM
The script must be after the links on the page and this:


action.linksclass3=function(){
alert('something new');
return false;

is missing a closing brace. Also, for:


action.linksclass2=function(){
document.getElementById("misterioProgram").style.display="block";
return false;
}

to work, you need one and only one element on the page with that exact id.

There could be other problems, I would need to see your page to be sure.

riptide
04-23-2007, 04:21 PM
I put it in the head of my document......fixing.

done, it works fine.

I have no idea why I put it up there.