0

In this plunk I have a directive that is declared with an UL element.

<directive>
  <ul>
    <li id="0">xxx 0</li>        
    <li id="1">xxx 1</li>        
    <li id="2">xxx 2</li>        
  </ul>
</directive>

I'm trying to retrieve these by analyzing the element parameter in the directive link function, but I only get them in the innerHTML. What I need is to get the id and text of the li elements as DOM. Any ideas?

angular.module('app', []);
angular.module('app').directive('directive', function() {
    var directive = {};
    directive.restrict = 'AE';
    directive.scope = true;
    directive.link = function(scope, element, attrs) {      
        console.log(element)
    };
    return directive;
});
3
  • do you want this result : plnkr.co/edit/baeGA2wbMuZkQRW5vlY7?p=preview Commented Oct 30, 2016 at 13:22
  • @Natiq No it is still plain text like that. Commented Oct 30, 2016 at 13:38
  • This seems really backwards. What generates the html in the first place? Commented Oct 30, 2016 at 13:58

2 Answers 2

1

Since you have element in directive you dont have to use querySelector,

you can directly do,

directive.link = function(scope, element, attrs) {
        console.log(element.find("ul")[0].children);
};

DEMO

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

1 Comment

this works, however it doesn't if the directive has a template, any idea how to fix this? see error in console plnkr.co/edit/Wy058Wqh2c7im0LhQQLC?p=preview
1

Yes you can. If you log the element then you will see that it is an array like object and you need to select the key of the array first in order to get the HTML element.

.directive('directive', function() {

var directive = {};
directive.restrict = 'AE';
directive.scope = true;
directive.link = function(scope, element, attrs) {
    console.log(element[0].querySelector('ul'));//Element is an array like object
};
return directive;

});

http://plnkr.co/edit/ajLmjxnDJ1JXjkk86aRh?p=preview

1 Comment

"Element is an array" ... no , it is an array like object.

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.