zibrnp Posted June 12, 2014 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 Link to comment Share on other sites More sharing options...
HartleySan Posted June 12, 2014 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? Link to comment Share on other sites More sharing options...
zibrnp Posted June 12, 2014 Author 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 Link to comment Share on other sites More sharing options...
Recommended Posts