5

I stumbled over this a couple times now so I decided to do some research, but found no one alse complaining about missing access to html attributes. These are my findings and I hope to get some more insights from the SFSE community.

I know we can access attributes of custom components that are part of our namespace:

<c:test aura:id="custom" foo="bar" />

var foo = cmp.find("custom").get("v.foo");

But the same seems not to work for html attributes:

<a aura:id="link" href="foo.bar">bar</a>

var link = cmp.find("link");

console.log(link);
console.log(link.toString());
console.log(link.getElement());
console.log(link.get("v.href"));

Results in:

enter image description here

It is a SecureComponent (not a SecureComponentRef like components from foreign namespaces), so why do I not have access to it's attributes? Why can't I even access its element? According to this DOM Access documentation I should have this kind of access! It didn't work in my aura:application, nor in my aura:component called by an action.

Switching on the Debug Mode for Lightning components it tells me:

Access Check Failed! AttributeSet.get(): attribute 'href' of component 'markup://aura:html {5:0} {a-element}' is not visible to 'markup://c:my {1:0}'.

Failing descriptor: {c:my}


There is one exception, where I was able to get the element and it's attributes. I had to let it throw an event and get the element out of the events context with pure javascript, but this is mostly not an option.

<a href="#" onclick="{!c.handleEvent}">trigger event</a>

handleEvent: function(cmp, evt, helper) {
    var url = evt.target.href;
},

Edit

Turned out link.getElement().href would work if it is not called onInit (as I did it) since elements are only available after rendering as defined here. So the the answer below is perfect since it works on init too.

1 Answer 1

6

This is actually because your link is converted to an aura:html. You could get the href like this:

    var link = component.find("link");
    console.log(link.get("v.HTMLAttributes").href);
6
  • smart, thank you! Any Idea why getElement() is null?
    – itsmebasti
    Commented Dec 3, 2017 at 19:32
  • 2
    @Basti salesforce.stackexchange.com/questions/147140 ...?
    – sfdcfox
    Commented Dec 3, 2017 at 20:20
  • solved it, and clarifies why cmp.find("link").getElement().href dind't work under these circumstances. Really appreciate your help!
    – itsmebasti
    Commented Dec 3, 2017 at 20:37
  • Hi @sfdcfox where did you found this get("v.HTMLAttributes")' ?? Please share source
    – user614946
    Commented Jun 26, 2019 at 13:07
  • @user614946 It's in the aura:html documentation (I just updated the link).
    – sfdcfox
    Commented Jun 26, 2019 at 14:32

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .