I want to create an element on the fly with attributes, NOT add them after the object is already created (setAttribute does not work).
Point: I have setup a web component to interact with it’s attributes inside it’s constructor (this.getAttribute). If you create an element on the fly (document.createElement) the attributes are empty. Setting them afterwards won’t work.
note: I know I can get the funcality I need in another way, this would just create the most user friendly version of the web component (minimal code).
class List extends HTMLElement {
constructor(temp) {
super();
if(this.getAttribute('att')!=null){
do stuff
}
}
}
other code
document.createElement('list')
2
Answers
here is a quick sample showing how to reference and set attributes within a web-component class definition.
You can’t reference attributes from the constructor, I think this is actually a static method, not an instance method.
connectedCallback() and likely? adoptedCallback will allow interaction with the element Object.
This demonstrates testing for an attribute, setting an attribute and value, and getting a value.
I use dataset https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset cause that is where custom values ideally should go.
Here is a playground showing when and when not attributes are available in the
constructor
https://jsfiddle.net/WebComponents/cxntaodk/
Run the code, explain for yourself what the
console
showsthe
constructor
only has access to attributes WHEN THE DOM WAS PARSEDsetting
innerHTML
causes a DOM parse and sets all attributes (which I think OP is asking)createElement
only runs the constructor, does not parse DOMThat is why the general advice is to not access attributes/DOM in the
constructor