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

170
Visualizações
Add one div ans class to one specific div if multiple div have the same class? (Javascript)

In a class exercise, (studying Javascript), I need to add a div with the class q6 under an existing div for the question 6. Teacher made it harder(at least for me), as all questions have div with class question.

Is there a way to select a specific div if they all have the same class?

Here's an example of the html code (I translated the question, as it was in french):

        <div id="content">
            <div class="question">
                <h2> Question 1. <span>(2pts)</span></h2>
                    Lorem ipsum
                <div class="q1"></div>
            </div>


            <div class="question">
                <h2>Question 2. <span>(2pts)</span></h2>
                    Lorem ipsum
                <div class="q2"></div>
            </div>


            <div class="question q3">
                <h2>Question 3. <span>(3pts)</span></h2>
                    Lorem ipsum
            </div>


            <div class="question">
                <h2>Question 4. <span>(3pts)</span></h2>
                    Lorem ipsum
            </div>


            <div class="question q5">
                <h2>Question 5. <span>(3pts)</span></h2>
                    Lorem ipsum
            </div>


            <div class="question">
                <h2>Question 6. <span>(2pts)</span></h2>
                <h3>
                    Add a div with class <code>q6</code> at the end of the <code>h3</code> in this 
                    question, in the <code>&lt;div class="question"&gt;</code>. If it's well 
                    placed, an orange square will appear. 
                </h3>
                <!-- You need to add the div here with javascript: <div class="q6"></div> -->
            </div>
         </div>

thanks for your answers

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

there are several ways to do it, here are some of them.

// fig 1
// use index
const questions = document.getElementsByClassName('question')
questions[5].innerHTML = 'fig 1 work'


// fig 2
// use data- prefix
// this should be the preferred way because this is easier to maintain
// when the list is dynamically created.
// also data- prefix is the least aggresive with web semantics
const target = document.querySelector(`.question[data-key='6']`)
if (target) {
  target.innerHTML += 'fig2 work'
}

// fig 3
// use multiple classes
const targetAlt = document.querySelector('.question.q6')
if (targetAlt) {
  target.innerHTML += 'fig3 work'
}
<div id="content">
  <div class="question">
    <h2> Question 1. <span>(2pts)</span></h2>
    Lorem ipsum
    <div class="q1"></div>
  </div>


  <div class="question">
    <h2>Question 2. <span>(2pts)</span></h2>
    Lorem ipsum
    <div class="q2"></div>
  </div>


  <div class="question q3">
    <h2>Question 3. <span>(3pts)</span></h2>
    Lorem ipsum
  </div>


  <div class="question">
    <h2>Question 4. <span>(3pts)</span></h2>
    Lorem ipsum
  </div>


  <div class="question q5">
    <h2>Question 5. <span>(3pts)</span></h2>
    Lorem ipsum
  </div>


  <div class="question q6" data-key="6">
    <h2>Question 6. <span>(2pts)</span></h2>
    <h3>
      Add a div with class <code>q6</code> at the end of the <code>h3</code> in this question, in the <code>&lt;div class="question"&gt;</code>. If it's well placed, an orange square will appear.
    </h3>
    <!-- You need to add the div here with javascript: <div class="q6"></div> -->
  </div>
</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

One of the best method will be

  • Select all the nodes with class question with document.querySelectorAll
  • Parse the list of nodes and search of h2 tag.
  • Check whether that h2 tage consist of text Question 6.
  • If this condition satisfies then that will be the target node.
  • Create a dic using document.createElement("div") and assign the className as q6. Append this new node to the node that have been identfied on previous step.

Working Fiddle

function addDiv() {
    const questionNodes = document.querySelectorAll('.question');   
    let searchNode;
    questionNodes.forEach((node) => {
        const questionNode = node.querySelector('h2');
        if (questionNode.innerHTML.includes('Question 6.')){
            searchNode = node;
        }
    });
    if(searchNode) {
        const newContent = document.createElement("div");
        newContent.className = 'q6';
        searchNode.appendChild(newContent);
    }
}
.q6 {
    width: 100%;
    height: 200px;
    background: brown;
}
<div id="content">
    <div class="question">
        <h2> Question 1. <span>(2pts)</span></h2>
        Lorem ipsum
        <div class="q1"></div>
    </div>


    <div class="question">
        <h2>Question 2. <span>(2pts)</span></h2>
        Lorem ipsum
        <div class="q2"></div>
    </div>


    <div class="question q3">
        <h2>Question 3. <span>(3pts)</span></h2>
        Lorem ipsum
    </div>


    <div class="question">
        <h2>Question 4. <span>(3pts)</span></h2>
        Lorem ipsum
    </div>


    <div class="question q5">
        <h2>Question 5. <span>(3pts)</span></h2>
        Lorem ipsum
    </div>


    <div class="question">
        <h2>Question 6. <span>(2pts)</span></h2>
        <h3>
            Add a div with class <code>q6</code> at the end of the <code>h3</code> in this
            question, in the <code>&lt;div class="question"&gt;</code>. If it's well
            placed, an orange square will appear.
        </h3>
        <!-- You need to add the div here with javascript: <div class="q6"></div> -->
    </div>
</div>

<button onclick="addDiv()">Add Div</button>

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