Jump to content
Larry Ullman's Book Forums

Changing "a Href" Label Value


Recommended Posts

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

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

 Share

×
×
  • Create New...