BonJon
BonJon

Reputation: 799

How to select elements in AngularJS

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!

Upvotes: 0

Views: 1344

Answers (2)

Matt
Matt

Reputation: 4752

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.

Upvotes: 1

Alessio Cantarella
Alessio Cantarella

Reputation: 5201

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.

Upvotes: 1

Related Questions