Skip to content
Related Articles

Related Articles

Improve Article

How to select an element by its class name in AngularJS ?

  • Last Updated : 14 Oct, 2020

Given an HTML document and the task is to select an element by its className using AngularJS.

Approach: The approach is to use the document.querySelector() method to get the element of a particular className. In the first example the element of className class1 is selected and its background color is changed to green. In the second example, 2 elements of same class are selected and some of the CSS is changed.

Example 1:




<!DOCTYPE HTML>
<html>
  
<head>
    <script src=
"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js">
    </script>
  
    <script>
        var myApp = angular.module("app", []);
        myApp.controller("controller", function ($scope) {
            $scope.getClass = function () {
                var el = angular.element(
                    document.querySelector(".class1"));
                el.css('background', 'green');
            };
        });
    </script>
</head>
  
<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
    <p>
        How to select an element by
        its class in AngularJS
    </p>
    <div ng-app="app">
        <div ng-controller="controller">
            <p class="class1">
                This is GeeksForGeeks
            </p>
            <input type="button" 
                value="click here" 
                ng-click="getClass()">
        </div>
    </div>
</body>
  
</html>     

Output:



Example 2:




<!DOCTYPE HTML>
<html>
  
<head>
    <script src=
"//ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js">
    </script>
  
    <script>
        var myApp = angular.module("app", []);
        myApp.controller("controller", function ($scope) {
            $scope.getClass = function () {
                var el = angular.element(
                    document.querySelectorAll(".class1"));
  
                el.css({ 
                    'background': 'green', 
                    'color': 'white' 
                });
            };
        });
    </script>
</head>
  
<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
    <p>
        How to select an element by 
        its class in AngularJS
    </p>
    <div ng-app="app">
        <div ng-controller="controller">
            <p class="class1">
                This is GeeksForGeeks
            </p>
            <p class="class1">
                A computer science portal
            </p>
            <input type="button" 
                value="click here" 
                ng-click="getClass()">
        </div>
    </div>
</body>
  
</html>    

Output:

Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :