Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

163
Visualizações
this.getAttribute('attribute') returning null even though attributes showing in this.attributes

I am working on creating some web components and trying to pull data in from the component attributes. When I console.log(this), it shows the correct element and the attributes associated. Same as when I console.log(this.attributes). However, if I console.log(this.getAttribute('attribute')) or console.log(this.hasAttribute('attribute')) I get back null and false respectively.

Can someone make sense of this? Here is the code I am working with:

index.html

<script src="component.js"></script>

<test-component test1="Test-text" test2=""></test-component>

component.js

const template = document.createElement('template');

template.innerHTML = `...`;

class TestComponent extends HTMLElement {

    constructor(){
        super();
        this.attachShadow({mode: 'open'});
        const shadow = this.shadowRoot;
        shadow.appendChild(template.content.cloneNode(true));
        console.log(this); // Shows correct element with attributes
        console.log(this.attributes); // Shows attributes
        console.log(this.getAttribute('test1')); // Returns null
        console.log(this.hasAttribute('test1')); // Returns false

    }
}

window.customElements.define('test-component', TestComponent);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Only in the connectedCallback does your CE exist in DOM.

In the constructor it is only pre-processed in memory, you can work with its shadowDOM, but the CE is not in the (main) DOM yet, thus you can not access attributes.

customElements.define('test-component', class extends HTMLElement {
    constructor(){
        super()
          .attachShadow({mode: 'open'})
          .innerHTML = `Content in shadowDOM`;
    }
    
    connectedCallback(){
        console.log(this.getAttribute('test1'));
    }
});
<test-component test1="A Attribute"></test-component>

BUT! There is a catch

If you define the CE after it is used in the DOM, the CE will be in the DOM and the constructor can read its attributes.

You should never rely on this behavior

A. Your CE user can load/define in the <head>

B. Your CE user can do let myCE = document.createElement("test-component")
which runs the constructor, but the connectedCallback will only run the moment .appendchild(myCE) executes

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda