[SalesForce] How to access HTML attributes in Lightning

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.

Best Answer

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);
Related Topic