Jess Jordan
Jess Jordan

Reputation: 21

check DOM element exist in js / angularjs

http://plnkr.co/edit/LZUa1tm7EROk8zcw6sGh?p=preview

angular.module('myModule', [])
  .controller('myDirective', function() {
    console.log(angular.element('.myClass').prop('offsetWidth'));
  }); 

I want to check where the DOM is visible or not in angularjs. But got an error of myClass is not a function?

Upvotes: 0

Views: 1088

Answers (2)

madhur
madhur

Reputation: 1001

Angular.element is different from document.getElementsByClassName. angular.element takes in an element, for eg-

var elem = angular.element('<div class="myDiv">{{ model.input }}</div>')

The above one is correct, but lets see the wrong version too

var elem = angular.element('.myDiv')

This one wont work

For your case do it like this :-

angular.element($document.find('div.myClass'))

Note :- you will have to inject $document in the controller, this way you can keep your whole code in angular format instead of using proper javascript methods like document.getElementsByClassName()

Hope it helps

Upvotes: 0

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

Change your controller name myDirective to myClass.

Try like this

angular.module('myModule', [])
  .controller('myClass', function($scope) {
    var mClass = document.getElementsByClassName("myClass");
    console.log(angular.element(mClass).prop('offsetWidth'));

  });

DEMO

N:B: DOM related task should be handled in the directive instead of controller.

Upvotes: 1

Related Questions