How to get the html element that is found in a given text?

Asked

Viewed 554 times

0

Talk personal, all right? I’m trying to solve the following question, but I’m not getting it. Could someone give me a hand?

I need to get the html element where a determining text is. That is, I go through a certain html block, find the text I need, but I did not find a way to get the html element to perform a determination action on it, example insert a class or remove the same.

Someone knows how to do it?

<div class="bloco1">
  <span>texto 1</span>
  <span>texto 2</span>
  <span>texto 3</span>
</div>

I would like to scroll through the block class element 1 to find text 1. In the span of this text I would like to insert or remove a class.

Grateful for the help!

  • Look I’ve been searching with Jquery, I hope I can help you: https://api.jquery.com/children/ Manipulating this span inside the Class bloco1 you can add or remove css in the <span>

1 answer

1

As far as I know, there are queries to search for elements by id, tag, classe, atributo, but not internal HTML. You will have to make a traditional loop for. Make a getElementsByClassName or querySelector to search for his element bloco1, then make a for in children (children) of that element.

Compare the internal HTML (innerHTML) or internal text (innerText) with the string you are looking for, and if found, add the class to that element.

The difference between internal HTML and internal text is that the text escapes from tags HTML, so if you have an element like <span><strong>Texto</strong></span>, the internal HTML of this element will be <strong>Texto</strong>, but the text will be Texto.

var bloco1 = document.querySelector('.bloco1')

// Exemplo utilizando laço for
for (var span of bloco1.children)
  if (span.innerText === 'texto 1')
    span.classList.add('red')

// Exemplo utilizando métodos do array
Array.from(bloco1.children)
  .filter(span => span.innerText === 'texto 3')
  .forEach(span => span.classList.add('orange'))
.red {
  color: red;
}

.orange {
  color: orange;
}
<div class="bloco1">
  <span>texto 1</span>
  <span>texto 2</span>
  <span>texto 3</span>
  <span>texto 1</span>
  <span>texto 2</span>
  <span>texto 3</span>
</div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.