Search code examples
angularjsjqlite

Why doesn't angular.element('<p>').css('color', 'red'); work?


Why doesn't angular.element('<p>').css('color', 'red'); work?

angular
  .module('app', [])
  .controller('MainController', MainController)
;

function MainController() {
  // angular.element('p').css('color', 'red'); ERROR. Now I see what the docs meant by "HTML String"
  // angular.element('<p>').css('color', 'red'); No error, but doesn't work
  angular.element(document.querySelector('p')).css('color', 'red'); // Works
}
<!DOCTYPE html>
<html ng-app='app'>

  <head>
    <script data-require="[email protected]" data-semver="1.4.6" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.6/angular.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller='MainController as vm'>
    <p>test</p>
  </body>

</html>


Solution

  • According to the docs, angular.element takes in an "HTML string or DOMElement to be wrapped into jQuery."

    The 2nd example doens't error out because you are in fact passing an HTML string. This will cause angular.element to return a newly created jQuery object instead of acting on an existing object.

    You can illustrate this by assigning the new element to a variable:

    var newElement = angular.element('<p>');

    This is equivalent to the behavior you would find in full jQuery:

    var newElement = $('<p>');

    The last example uses querySelector which returns the actual HTML DOM element. This is what Angular needs to operate on that existing element (unless you've included jQuery - then you can use selectors like you would in jQuery/example 1).