0

I have to identify all the elements having class in-brackets and add an attribute href="#" to them. I have to do this without jQuery.

This is my code example now:

<a class="in-brackets">Banana</a>
<a class="in-brackets">Apple</a>

In my Controller:

document.getElementsByClassName("in-brackets").setAttribute("href", "#");

But nothing happens. The element doesn't have the attribute.

2
  • 2
    Have you read How do I "think in AngularJS" if I have a jQuery background? Commented Apr 7, 2014 at 12:51
  • @JoseM excellent resource! The point of this link is to think about why you're trying to set href to #. My guess based upon my experiences is that the links aren't showing as links, which I've solved via CSS: a{cursor: pointer;} Commented Apr 7, 2014 at 13:03

3 Answers 3

2

The "Angular way" is to only do DOM manipulation inside a directive.
You can build a custom directive for that:

.directive('inBrackets', function () {
    return {
        restrict: 'C',
        link: function postLink(scope, elem, attrs) {
            attrs.$set('href', '#');
        }
    };
});

Read more about custom directives and the various properties of the "Directive Definition Object" here.

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

Comments

1

You'll have to iterate the elements:

var elems = document.getElementsByClassName("in-brackets");

for (var i = 0; i < elems.length; i++) {
    elems[i].setAttribute("href", "#");
}

1 Comment

While correct in general, direct DOM manipulation is against the Angular philosophy (and highly discouraged in an Angular app).
0

Have you tried jqLite bundled with AngularJS? It works similarly to jQuery (though only the most used features are supported); you might feel comfortable with it if you have a jQuery background.

angular.element(document.getElementsByClassName("in-brackets")).attr("href", "#");

Comments

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.