Jump to content

Archived

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

FrOzeN

GetElementBy

Recommended Posts

I'm trying to modify some properties with JavaScript by using there class name. Can anyone tell me what's wrong with the following example, and/or an alternative to do it correctly?

[code]<html>
<head>
<title></title>
</head>
<body>

<span class="classname">Test</span>

(script type="text/javascript">
  document.getElementByClass("classname").innerHTML = "Example worked!";
</script>

</body>
</html>[/code]

Thanks.

Share this post


Link to post
Share on other sites
there is no function getElementByClass unless you have written it yourself. you've got to remember that several elements can hold the same class. you can either use getElementById and do it with an ID if you only have one element you're wanting to return, or else, you can cycle through all a specific type of element with the class you're looking for like this:
[code]
elements = document.getElementsByTagName("SPAN");
for (i = 0; i < elements.length; i++) {
  if (elements[i].className == 'classname') {
    // do your thing here
    elements[i].innerHTML = "Example worked!";
  }
}
[/code]

hope this helps!

Share this post


Link to post
Share on other sites
And if you're going to be doing that repeatedly throughout the page, you should cache the results.

Share this post


Link to post
Share on other sites
[quote author=fenway link=topic=108913.msg438702#msg438702 date=1158844632]
And if you're going to be doing that repeatedly throughout the page, you should cache the results.
[/quote]

good point, once again. boy, i'm glad you're here to help clean up after me ;)

Share this post


Link to post
Share on other sites
Thanks, that's what I was looking for.

Sorry about the post, my router is setup to cut me off at 10:30 pm weeknights so I don't spend all night on the net, and I rushed to post it before it cut me off. When I clicked post some error occurred when posting '<' and '>' so I quickly changed them to brackets figuring you guys could make sense of what I meant and accidently duped half the post when copying + pasting in a rush.

[EDIT] I just cleaned up the post and found the bug that stopped it from posting correctly the first time. When trying to post the line below it firefox returns the error, "The connection to the server was reset while the page was loading."

<sc[b][/b]ript type="text/javascript">

Note: I've used a BBCode trick to avoid the error by adding "[[b][/b]b][/[b][/b]b]" within the line.

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.