FrOzeN Posted September 21, 2006 Share Posted September 21, 2006 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. Quote Link to comment Share on other sites More sharing options...
obsidian Posted September 21, 2006 Share Posted September 21, 2006 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! Quote Link to comment Share on other sites More sharing options...
fenway Posted September 21, 2006 Share Posted September 21, 2006 And if you're going to be doing that repeatedly throughout the page, you should cache the results. Quote Link to comment Share on other sites More sharing options...
obsidian Posted September 21, 2006 Share Posted September 21, 2006 [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 ;) Quote Link to comment Share on other sites More sharing options...
FrOzeN Posted September 22, 2006 Author Share Posted September 22, 2006 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. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.