Steve Voltmer
Steve Voltmer

Reputation: 43

Change CSS attributes on part of a HTML element's innerHTML with Javascript

I have been trying to find a way to change part of the innerHTML of several elements with the class .studentYear, but I keep getting a JavaScript undefined error. Here's what I am trying.

JavaScript:

document.getElementsByClassName('studentYear').innerHTML.indexOf(" ").css('color', '#800000');

HTML:

<div class="accordionContainer">
      <div class="studentYear">Freshman (A1 Schedule)</div>
        <div class="accordionContent" style="display:none;">
            <p class="studentTerm">Fall</p>
           <p>Content</p>
        </div>
</div>

I see now that it is a collection (array type). I need to access the innerHTML for each item in the collection and change the style attribute on only part of the innerHTML, in this case everything in parentheses "(A1 Schedule)". I still get the undefined error if following the suggestions made below.

Upvotes: 1

Views: 2880

Answers (2)

user1289451
user1289451

Reputation: 921

As the comments have said, you have to loop through the objects and set each one since it is similar to an array. Something like this:

var items = document.getElementsByClassName('studentYear');

for (var i = 0; i < items.length; i++) {
  items[i].setAttribute('style', 'color: #F00');
}

Edit: Just saw samanime's answer, which seems a little more elegant in my opinion.

Upvotes: 0

samanime
samanime

Reputation: 26527

There are a number of problems with what you're trying.

  • document.getElementsByClassName returns an HTMLCollection, which is kind of like an array, but not quite, so you can't call innerHTML on it directly
  • indexOf(" ") will give you the first index of the space, which would possibly be before the element. It would also give you a number.
  • css() doesn't exist in vanilla JavaScript, that's a jQuery thing.

It looks like you're wanting to set that element to use color: #000000. That means you actually need to set the style attribute.

This code would do the trick, applying it to every one of them with the class studentYear.

Array.prototype.forEach.call(document.getElementsByClassName('studentYear'), function (element) {
    element.style = 'color: #F00';
});

The Array.prototype.forEach.call lets us treat the HTMLCollection as an array and loop through it. Then for each element, we'll set it's style attribute to color: #F00 (or whatever you want, I used red to make it obvious).

If you need to support older browsers, you shouldn't access the style attribute directly, instead use setAttribute instead:

element.setAttribute('style', 'color: #F00');

Upvotes: 5

Related Questions