0

I am trying to use AngularJS to grab the element by tag name.

For example,

angular.element(document.querySelector('h1')).css('color', 'green');

element in HTML:

<div>
    <h1>Title 1</h1>
</div>
<div>
    <h1>Title 2</h1>
</div>

It works only for the first element but not the second one. I am not sure the reason for it. Can anyone help me about it? Thanks a lot!

3
  • 4
    The reason is that querySelector() selects first matching element. You can use querySelectorAll to select all matched elements, loop over them and apply styles. However, I'd suggest to use ng-class with a flag on those elements. Commented Feb 11, 2016 at 16:41
  • 1
    why are you trying to do this? Angular is not jQuery. Just use ng-class Commented Feb 11, 2016 at 16:46
  • If it's like you describe, maybe you should also be using ng-repeat as in <div ng-repeat="title in titles"><h1 ng-class="{'color': title.color}">{{title.text}}</h1></div>. It depends on what you're trying to accomplish, but make sure you're trying to do things the "Angular" way. See this for more info: stackoverflow.com/questions/14994391/… Commented Feb 11, 2016 at 16:56

2 Answers 2

1

As @Tushar mentioned, the best way to handle this is with ng-class. Let Angular do the DOM manipulation for you

Your CSS

.someclass{
  color: green
}

Your HTML

<div ng-class="{'someclass': obj.value == 'somevalue'}">
    <h1>Title 1</h1>
</div>
<div>
    <h1>Title 2</h1>
</div>

After 'someclass', in your controller, you can insert whatever expression makes the most sense. When your expression evaluates to true, the 'someclass' will be applied to your Div.

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

Comments

1

The querySelector() method returns the first element that matches a specified CSS selector(s) in the document.

The querySelectorAll() method returns all elements in the document that matches a specified CSS selector(s), as a static NodeList object.

1 Comment

That explains why the code is not working, but doesn't provide solution.

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.