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

159
Visualizações
get access to html tags inside innerHTML | javascript

I'm trying to create variable from a class inside the innerHTML down here:

ruleData.forEach((rule) => {
        rulesWrapper.innerHTML += `
        <div class='rule'>
          <div id='rule-title' class='rule-title' onclick='showRuleDetail(${counter})'>
            <div>
              <p>${counter}.</p>
              <p>${rule.title}</p>
            </div>
            <svg width="20" height="21" viewBox="0 0 20 21" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M12.5 5.5L7.5 10.5L12.5 15.5" stroke="#1E1E20" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </div>
          <div class='rule-body'>
            <p>${rule.body}</p>
          </div>
        </div>
      `;
        counter++;
      });

For example I want to target rule-body class inside this innerHTML and change it's background

like this:

let ruleBody = document.querySelectorAll('.rule-body');

ruleBody[0].style.background = 'red';

But this doesn't work ,I get this error:

TypeError: Cannot read properties of undefined (reading 'style')
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You must access the .rule-body after the innerHTML and make sure it is indeed in the DOM. Then, this should work perfectly fine:

const container = document.querySelector("#container");
const button = document.querySelector("#button");

function exec() {
  container.innerHTML = `<div class='rule-body'>yo</div>`;
  const ruleBody = document.querySelectorAll('.rule-body');
  ruleBody[0].style.backgroundColor = 'red';
}

button.onclick = exec;
<div id="container">
  
</div>

<button id="button">
    CLICK TO INSERT
</button>

about 4 years ago · Juan Pablo Isaza Relatório

0

You can use DOMParser for this

ruleData.forEach((rule) => {
    let rule_html = `
        <div class='rule'>
            <div id='rule-title' class='rule-title' onclick='showRuleDetail(${counter})'>
                <div>
                    <p>${counter}.</p>
                    <p>${rule.title}</p>
                </div>
                <svg width="20" height="21" viewBox="0 0 20 21" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M12.5 5.5L7.5 10.5L12.5 15.5" stroke="#1E1E20" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
                </svg>
            </div>
            <div class='rule-body'>
                <p>${rule.body}</p>
            </div>
        </div>
    `;
    let rule = new DOMParser().parseFromString(rule_html,"text/xml").firstChild;
    rule.querySelector('.rule-body').style.background = 'red';
    rulesWrapper.appendChild(rule);
    counter++;
});

Also if the counter is the index of the ruleData you can use forEach's index as well. (rule,i)=>{

about 4 years ago · Juan Pablo Isaza Relatório

0

I suggest to map and delegate

const ruleData = [{"title":"Title 1","body":"This is the body"},{"title":"Title 2","body":"This is the body"}]
const rulesWrapper = document.getElementById("rulesWrapper");
rulesWrapper.innerHTML = ruleData.map((rule,i) => `
        <div class='rule'>
          <div class='rule-title' data-idx='${i}'>
            <div>
              <p>${i}.</p>
              <p>${rule.title}</p>
            </div>
            <svg width="20" height="21" viewBox="0 0 20 21" fill="none" xmlns="http://www.w3.org/2000/svg">
            <path d="M12.5 5.5L7.5 10.5L12.5 15.5" stroke="#1E1E20" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
            </svg>
          </div>
          <div class='rule-body'>
            <p>${rule.body}</p>
          </div>
        </div>
      `).join("");

rulesWrapper.addEventListener("click", function(e) {
  const tgt=e.target.closest(".rule-title");
  if (tgt) console.log(tgt.dataset.idx)
})
<div id="rulesWrapper"></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