zibrnp 0 Posted June 12, 2014 Report Share Posted June 12, 2014 Hello I want to change value of a href label and need to reference it using class name.I did: <html> <head> <title>test</title> </head> <body> <a class="class_id" href="#">Older Post</a> </body> <script type="text/javascript"> window.onload = init; function init() { 'use strict'; var to_replace = document.getElementsByClassName('class_id'); to_replace.innerHTML = "Older"; } </script> </html> When using in html id and getElementById everything works but not with getElementsByClassName.Can you guys suggest solution please?Thanks T Quote Link to post Share on other sites
HartleySan 826 Posted June 12, 2014 Report Share Posted June 12, 2014 It doesn't work because getElementsByClassName returns an array (technically, a node list, which is an array-like structure). My advice would be to use querySelector and querySelectorAll instead of getElementsByClassName, as the former have better browser support and are easier to use in all cases. If there is only one element in the DOM with a given class name, then you can use querySelector and reference the returned element like getElementById. However, if you need to capture multiple elements, then you will need to use querySelectorAll/getElementsByClassName, and loop through the results set. As a side note, innerHTML does not change the href of the link, it changes the text within the opening and closing tags. That help? Quote Link to post Share on other sites
zibrnp 0 Posted June 12, 2014 Author Report Share Posted June 12, 2014 OMG I can not believe I forgot that it returns array (the same mistake again) .Anyway thank you very much.T Quote Link to post Share on other sites
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.
Note: Your post will require moderator approval before it will be visible.