Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

169
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda