gondolator
gondolator

Reputation: 71

How to check if an <li> element has a specific value

can i Check with JS or JQuery whether an list contains a specific Value or not?

My Code:

HTML:

  <ul class="list-group list-group-flush" id="liste">
  </ul>

JavaScript:

<script type="text/javascript">
  document.getElementById('Add').onclick = function() {
    var Nutzer = document.getElementById('Suche').value;
    var Liste = document.getElementById('liste');
    if (! $("li:has(Test)")) {
      var entry = document.createElement('li');
      entry.setAttribute( 'class', 'list-group-item' );
      entry.appendChild(document.createTextNode(Nutzer));
      Liste.appendChild(entry);
    }
}
</script>

I only found Solutions with li:contains but that is not what I want.

Upvotes: 2

Views: 3286

Answers (2)

Diogo Lessa
Diogo Lessa

Reputation: 177

You can do it with only vanilla JS actually...

Take a look:

HTML:
  <ul>
      <li>Banana</li>
      <li>Apple</li>
      <li>Test</li>
      <li>Cucumber</li>
      <li>Coconut</li>
  </ul>

JS:
  const li = document.querySelectorAll('ul li');
  for (let i = 0; i < li.length; i++) {
    // it is the same as contains
    if (/Test/g.test(li[i].textContent)) {
        console.log('I am the <li> you want', li[i])
    }
    // it is the same as equal to
    if (li[i].textContent === 'Test') {
        console.log('I am the <li> you want', li[i])
    }

  }

Cheers,

Upvotes: 2

Archie
Archie

Reputation: 911

Use Array.prototype.some on the list of li elements

console.log([...$("#liste li")].some(el => $(el).text() === "Test"));
console.log([...$("#liste li")].some(el => $(el).text() === "Anything Else"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="list-group list-group-flush" id="liste">
  <li>Test</li>
</ul>

Upvotes: 3

Related Questions