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

136
Visualizações
js address specific element

I have got a search function on a specific text with verses, which is structured like the sample text below.
The 1st line of each verse has got a verse number at the beginning. My search function works fine. It searches for a word and saves the whole line in which the word occurs in an array and prints it in the "rslt" element.
Now I would like to save the verse number of the found line and if it doesn't have one, than it should take it from the line above. Have you got an idea how I could achieve this?

function srch() {
  var input, filter, p, cache, resultEl;
  input = "MTV";
  cache1 = [];
  resultEl = document.getElementById('reslt');
  p = document.getElementsByTagName('p');

  for (i = 0; i < p.length; i++) {
    if (p[i].innerHTML.indexOf(input) > -1) {
      cache1.push(p[i].innerHTML); /*save results in array*/
    }
  }
  if (cache1.length > 0) {
    for (i = 0; i < cache1.length; i++) {
      resultEl.innerHTML = resultEl.innerHTML + cache1[i] + "<br>"; /*write results*/
    }
  }
}
<div><button onclick="srch()">Search</button></div>
<div id="reslt"></div>
<p class="1stline"><span class="verse-nr">1 </span>The quick, brown fox jumps over a lazy dog.</p>
<p class="xline"> DJs flock by when MTV ax quiz prog.</p>
<p class="1stline"><span class="verse-nr">2 </span> Junk MTV quiz graced by fox whelps.</p>
<p class="xline"> Bawds jog, flick quartz, vex nymphs.</p>
<p class="1stline"><span class="verse-nr">3 </span> Waltz, bad nymph, for quick jigs vex!</p>
<p class="xline"> Fox nymphs grab quick-jived waltz.</p>
<p class="xline">Brick quiz whangs jumpy veldt fox.</p>
<p class="xline">Bright vixens jump; dozy fowl quack.</p>
<p class="1stline"><span class="verse-nr">4 </span>Quick wafting zephyrs vex bold Jim. </p>
<p class="xline">Quick zephyrs blow, vexing daft Jim.</p>

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

0

Here is one solution using .previousElementSibling.

Test to see if there is a <span> tag, if so, the verse # is there, otherwise concatenate the previous element's HTML with the search result Then push the result onto your array,

Check comments in code in srch() function:

function srch() {
  var input, filter, p, cache, resultEl;
  input = "MTV";
  cache1 = [];
  resultEl = document.getElementById('reslt');
  p = document.getElementsByTagName('p');

  for (i = 0; i < p.length; i++) {
    if (p[i].innerHTML.indexOf(input) > -1) {
      // if it includes a span, it includes the verse #
      if (p[i].querySelector('span')) {
        cache1.push(p[i].innerHTML); /*save results in array*/
        // otherwise, get the previous siblings HTML too
      } else {
        cache1.push(p[i].previousElementSibling.innerHTML + p[i].innerHTML);
      }
    }
  }
  if (cache1.length > 0) {
    for (i = 0; i < cache1.length; i++) {
      resultEl.innerHTML = resultEl.innerHTML + cache1[i] + "<br><br>"; /*write results*/
    }
  }
}
<div><button onclick="srch()">Search</button></div>
<div id="reslt"></div>
<p class="1stline"><span class="verse-nr">1 </span>The quick, brown fox jumps over a lazy dog.</p>
<p class="xline"> DJs flock by when MTV ax quiz prog.</p>
<p class="1stline"><span class="verse-nr">2 </span> Junk MTV quiz graced by fox whelps.</p>
<p class="xline"> Bawds jog, flick quartz, vex nymphs.</p>
<p class="1stline"><span class="verse-nr">3 </span> Waltz, bad nymph, for quick jigs vex!</p>
<p class="xline"> Fox nymphs grab quick-jived waltz.</p>
<p class="xline">Brick quiz whangs jumpy veldt fox.</p>
<p class="xline">Bright vixens jump; dozy fowl quack.</p>
<p class="1stline"><span class="verse-nr">4 </span>Quick wafting zephyrs vex bold Jim. </p>
<p class="xline">Quick zephyrs blow, vexing daft Jim.</p>

about 4 years ago · Juan Pablo Isaza Relatório

0

If I was you I would create a new function to a find a verse number and it would be something like this

var p = document.getElementsByTagName('p');
      
function srch() {
        var input, filter, cache, resultEl;
        input = "MTV";
        cache1= [];
        resultEl = document.getElementById('reslt');
    
        for (i = 0; i < p.length; i++) {
            if (p[i].innerHTML.indexOf(input) > -1) {
                cache1.push(p[i].innerHTML); /*save results in array*/
                var verseNumber =  findVerseNumber(i);
                console.log(verseNumber)
            }
        }     
     
      
        if (cache1.length>0){
            for (i = 0; i < cache1.length; i++) {
                resultEl.innerHTML = resultEl.innerHTML + cache1[i]+"<br>"; /*write results*/
            }
        }
    }


 function findVerseNumber(index){
      var verseNumber;
      for (j = index; j >= 0; j--) {
           if (p[j].querySelector('span')) {
            verseNumber = p[j].querySelector('span').innerHTML.trim();
              break;
          } 
        }  
      return verseNumber;
    }

Html

<div><button onclick="srch()">Search</button></div>
        <div id="reslt"></div>
        <p class="1stline"><span class="verse-nr">1 </span>The quick, brown fox jumps over a lazy dog.</p>
        <p class="xline"> DJs flock by when MTV ax quiz prog.</p>
        <p class="1stline"><span class="verse-nr">2 </span> Junk MTV quiz graced by fox whelps.</p>
        <p class="xline"> Bawds jog, flick quartz, vex nymphs.</p>
        <p class="1stline"><span class="verse-nr">3 </span> Waltz, bad nymph, for quick jigs vex!</p>
        <p class="xline"> Fox nymphs grab quick-jived waltz.</p>
        <p class="xline">Brick quiz whangs jumpy veldt fox.</p>
        <p class="xline">Bright vixens jump; dozy fowl quack.</p>
        <p class="1stline"><span class="verse-nr">4 </span>Quick wafting zephyrs vex bold Jim. </p>
        <p class="xline">Quick zephyrs blow, vexing daft Jim.</p>
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