Jump to content
Larry Ullman's Book Forums
Sign in to follow this  
zibrnp

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

Share this post


Link to post
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?

Share this post


Link to post
Share on other sites

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.   Paste as plain text instead

  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.

Loading...
Sign in to follow this  

×
×
  • Create New...