Skip to content
Advertisement

document.querySelector() is not applying style

Could someone point my mistake

here ?

<p ng-controller="demo" class='bgColor'>
  This is dummy content
</p>

angular.module("app", [])

  .controller("demo", function($scope) {
    $scope.p = document.querySelector('.bgColor');

    var styles = {
      'background-color': 'red'
    };
    Object.assign($scope.p.style, styles);
  });

I’m trying to modify the class the property but am actually getting TypeError: Cannot read property ‘style’ of null in my Angular.js 1.x application. But when try in fiddle, I couldn’t see the error but also style is not applied.

Thanks every one

Advertisement

Answer

Please see the following working snippet. Also keep in mind that AngularJS documentation discourages using controllers to manipulate the DOM.

angular.module("app", [])

  .controller("demo", function($scope) {
    $scope.p = document.querySelector('.bgColor');

    Object.assign($scope.p.style, {
      'background-color': 'red'
    });
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>

<p ng-app="app" ng-controller="demo" class="bgColor">
  This is dummy content
</p>
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement