Open In App

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

Given an HTML document and the task is to select an element by its className using AngularJS. The elements can be selected with the help of a class name using the document.querySelector() method that is used to return the first element that matches a specified CSS selector(s) in the document.

Approach: The approach is to use the element of className class1 that will be selected and its background color is changed to green, by using the document.querySelector() method.

Example 1: This example illustrates for selecting the element by its class name in AngularJS.






<!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>
    <h3>
        How to select an element by
        its class in AngularJS
    </h3>
    <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: In this example, the 2 elements of same class are selected and some of the CSS is changed.






<!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>
    <h3>
        How to select an element by
        its class in AngularJS
    </h3>
    <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:

 


Article Tags :