1

I am trying to add a class to multiple divs to change it's background color.

HTML:

<div class="span6">
    <div class="heading">Heading 1</div>                     
</div>

I am currently using this:

angular.element(document.querySelector('.heading')).addClass('color-change');

My issue is that... there are multiple div's with this heading but it is changing the color of only the first occurrence of that div. How can I have it so all the divs with that class add that css styling.

2 Answers 2

3

document.querySelector selects the first element that matches the query. querySelectorAll should achieve the result you want.

JSFiddle: https://jsfiddle.net/usw4cozt/

Sign up to request clarification or add additional context in comments.

2 Comments

Although this is answer is correct, it's not how you would do it in Angular
Agreed, I would rather use ng-class or class={{expression}} but I won't fault anyone for using native JS, especially if they have some reason they don't want that element bound so strongly to the controller (which they may or may not, idk).
1

Use ng-class instead of class and assign a className to your model :

<h1 ng-class='mainCtrl.selectedTheme'>Title 2</h1>

angular.module('demoApp', [])
  .controller('MainController', MainController)

function MainController() {
  this.selectedTheme = 'blue';
}

https://jsfiddle.net/4tuavhL2/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.