AngularJS element.innerHTML is undefined from within directive

26,913

The element variable that is passed to your link function is a jqLite object - not a DOM object. You can obtain the DOM object with element[0] (like you could in jQuery), but jqLite provides a method for you: element.html(). Check out the docs.

Share:
26,913
Robert Christian
Author by

Robert Christian

Software architect and polyglot developer currently using S/O for the Java, Python, NodeJS, Javascript, Vert.x, client MVC frameworks, open source, cloud platform, and algorithms communities.

Updated on February 11, 2020

Comments

  • Robert Christian
    Robert Christian over 4 years

    Let's say I have:

    directives.directive('foo', function () {
        return {
            restrict:'A',
            scope: true,
            link:function (scope, element, attr) {
    
                console.log('innerHTML is ' + element.innerHTML);
    
                scope.$watch('update', function (newValue) {
                    console.log('innerHTML is... ' + element.innerHTML);
                });
    
            }
        }
    });
    

    ... then innerHTML is undefined. I imagine this is due to the way Angular processes the DOM. What is the right way to obtain the innerHTML?

  • Robert Christian
    Robert Christian over 11 years
    Thank you. Exactly what I was missing.