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!

Felix G.
  • 6,365
  • 2
  • 16
  • 24
BonJon
  • 779
  • 1
  • 7
  • 21
  • 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. – Tushar Feb 11 '16 at 16:41
  • 1
    why are you trying to do this? Angular is not jQuery. Just use ng-class – Ales Maticic Feb 11 '16 at 16:46
  • If it's like you describe, maybe you should also be using `ng-repeat` as in `

    {{title.text}}

    `. 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: http://stackoverflow.com/questions/14994391/thinking-in-angularjs-if-i-have-a-jquery-background
    – adam0101 Feb 11 '16 at 16:56

2 Answers2

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.

Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
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.

Matt
  • 4,462
  • 5
  • 25
  • 35