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

104
Visualizações
trying to create a simple selector function

I want to create a function called with a single parameter that will accept any valid CSS selector by using the querySelectorAll method.

The function should return two methods to mimic the .css and .html from jq.

I'm pulling my hair out with this one. Can anyone help? This is all I have come up with so far and can't get figure it out:

const $ = (selector) => {
    let element = document.querySelectorAll(selector);
    return {
        html: function(content) {
            element.innerHTML = content;
        }
    }
};
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Since you're picking up a list of nodes you need to find some way to iterate over them. Save your query to your returned object, add a new method called loop that can accept a callback and then iterate over the elements retrieved by the query with the callback provided by html and css. Note: return this means you can chain methods together like jQuery allows. It simply returns the object again.

function $(selector) {

  return {

    // Cache the query
    query: document.querySelectorAll(selector),

    // `loop` accepts a function (callback)
    // and calls it on each element in the query
    loop: function (cb) {
      this.query.forEach(el => cb(el));
    },

    // Call `loop` and for each element change the content
    html: function(content) {
      this.loop(el => el.innerHTML = content);
      return this;
    },

    // Call `loop` and for each element change the style
    css: function(prop, value) {
      this.loop(el => el.style[prop] = value);
      return this;
    }

  }

};

// Get all the divs with red class properies
$('div.red')
  .html('Updated')
  .css('background-color', 'red')
  .css('color', 'white');
<div>1</div>
<div class="red">2</div>
<div>3</div>
<div class="red">4</div>

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