Jump to content

GetElementBy


FrOzeN

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.
Link to comment
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!
Link to comment
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.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.