2

I have a simple directive and I'd like to access one of its inner DOM element to add a class to it.

div(my-directive)
  div
    // some html
    span.myDiv
       | some text

My HTML has much more elements than this so accessing .myDiv via the .childen() method is quite tedious.

I've tried the following which doesn't work:

.directive('myDiv', ['$compile', function($compile) {
  return {
    restrict: 'A',
    link: function(scope, element) {
      var el = element[0].getElementsByClassName('myDiv')

      angular.element(el).addClass('myAwesomeClass')
      $compile(el)(scope)

    }
  }
}])

How can I do this?

Many thanks

1
  • ok, why would you need to do that? but if you do need to do some complex css selector operation i would advice to use something like sizzle. how ever 90% of the manipulation you would need to do to the DOMcan be done via data binding and templating Commented Jan 30, 2015 at 14:26

1 Answer 1

2

You can use document.querySelector to find the target element to add the class. $compile(el)(scope) is not required here when you add a class using angular.

JSBin Preview

JsBin Edit

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

1 Comment

you can use element[0].querySelector than you only search in the subtree under the directive

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.