user3757605
user3757605

Reputation: 442

How to get span text by its class?

I need to get the text in a span element. The problem is that it doesn't have an unique ID, only a class. Is there a way to retrieve the text inside this element by knowing only its class?

I tried this code:

var theValue = document.getElementById('you').getElementsByClassName('username').innerHTML;

but I got an error:

Uncaught TypeError: Cannot read property 'getElementsByClassName' of null

HTML:

<div id="you">
       <span class="username">theTextIShouldGet</span>

        <a class="logout" href="/logout">
         </a>
        <a class="settings" href="/settings">
         </a>
</div>

Upvotes: 0

Views: 4407

Answers (1)

tymeJV
tymeJV

Reputation: 104775

You get that error because you're trying to access that element before it's loaded on the page. Move your script to the bottom of the page or wrap you script in a DOM ready function.

As for getting the text by class, sure! getElementsByClassName returns a collection - so you'll need to reference the index you want:

<div id="you">
   <span class="username">theTextIShouldGet</span>

    <a class="logout" href="/logout">
     </a>
    <a class="settings" href="/settings">
     </a>
</div>
<script>
    var theValue = document.getElementById('you').getElementsByClassName('username')[0].innerHTML;
</script>

Upvotes: 5

Related Questions