Is there a way to verify the presence of a particular value in a list?

I need to validate the content of all li tags within a ul list. If any list item contains the text "None," then I want to append specific text to a div. If no li tag includes "None," then different text should be added to the div.

Upon checking my code, I encountered the following error in the console:

Uncaught TypeError: can't access property "includes", mylist.textContent is undefined

It appears that I may not be utilizing the .includes() method properly.

var mydiv = document.querySelector("#mydiv");
var mylist = document.querySelectorAll("#mylist li");
var myresult = mylist.textContent.includes("None");

if (myresult == true) {
  mydiv.textContent = "Result is True";
} else {
  mydiv.textContent = "Result is False";
}
My HTML:

<ul id="mylist">
  <li>item 1</li>
  <li>item 2</li>
  <li>None</li>
  <li>item 4</li>
  <li>item 5</li>
  <li>item 6</li>
  <li>item 7</li>
</ul>

<ul id="mydiv">
</ul>

Answer №1

querySelectorAll function retrieves a list of elements, making it impossible to directly check the textContent of a specific element.

I recommend converting the list into an array using spread syntax to enable the use of array methods. You can then utilize some method to evaluate your condition.

var mydiv = document.querySelector("#mydiv");
var mylist = document.querySelectorAll("#mylist li");
var myresult = [...mylist].some(item => item.textContent.includes("None"));

if (myresult === true) {
  mydiv.textContent = "Result is True";
} else {
  mydiv.textContent = "Result is False";
}
<ul id="mylist">
  <li>item 1</li>
  <li>item 2</li>
  <li>None</li>
  <li>item 4</li>
  <li>item 5</li>
  <li>item 6</li>
  <li>item 7</li>
</ul>

<ul id="mydiv">
</ul>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring various queries in Firestore

Does anyone know if there is a way to create a sentence similar to this one: return this.db.collection('places', ref => ref.where("CodPais", "<>", pais)).valueChanges(); I have tried using != and <> but neither seem to be valid. Is the ...

The issue with GatsbyJS and Contentful: encountering undefined data

Within the layout folder of my project, I have a Header component that includes a query to fetch some data. However, when I attempt to log this.props.data in the console, all I get is 'undefined'. Could someone please point out where I might be m ...

The Child component is unable to render initially due to the Context API being undefined during the first render of the Child component

I'm struggling to ensure that a child component only renders when the Context API state I've set up is fully mounted. The Parent component fetches data from the server and sets the state based on the received information. Initially, I keep gettin ...

Navigating to a different page using the browser address bar causes the context to be reset

Upon receiving the user's data from the API on the login page, it is set in the user context. Subsequently, upon redirection to the AdminPanelApp, the data within the user context is displayed accurately. However, if I am in the AdminPanelApp and navi ...

Incorporating lodash into Angularjs for enhanced functionality

After stumbling upon an app online that utilizes AngularJS with Lodash, I noticed a simple way in which Lodash is incorporated. By including the following line in the body (after angular has been included): <script src='vendor/lodash/3.3.1/lodash. ...

Node-fetch enables dynamic requests

Seeking to retrieve real-time data from a fast-updating API has posed a challenge for me. The issue lies in my code constantly returning the same value. I've experimented with two approaches: var fetch = require("node-fetch"); for(let i=0; i<5; i+ ...

Looking for assistance with reviewing and optimizing Angular UI-Router implementation

I'm currently facing an issue with setting up routing for my angular portfolio. Despite checking my code against a previous app, I am unable to identify the error as there are no console logs when I compile. Can someone please review my code layout an ...

Keep JS Accordion open when links are clicked

Utilizing PHP, I am fetching items from a database and creating an HTML table to display each item. Adjacent to the HTML table, there is a side menu with an accordion function implemented in JavaScript. Within each accordion section, there are links for ...

How to access vue.js 3 single file component functions from within a script tag

Imagine having a single file component structured like this: <template> // content irrelevant </template> <script> export default { data() { return { redLocations: [ "Isfahaan", "Qom", ...

Pause a YouTube video automatically when the window is not in focus using FancyBox

I have successfully implemented dynamic play/pause functionality for a YouTube video, as demonstrated in my weave. However, I am facing challenges in making it work dynamically with FancyBox using the onBlur event (to pause the video when the window is no ...

Creating dynamic and engaging animations for components using ReactCSSTransitionGroup

I'm currently attempting to add animation to a modal that appears when a button is clicked using ReactCSSTransitionGroup. The modal is showing up on button click, however, there is no transition effect. My render method is set up like this: render() ...

View is unable to trigger the success attribute

Currently, I am delving deep into Backbone JS and facing an issue where the 'success' function in 'EditUser' is not being triggered. I would greatly appreciate it if someone could guide me on what changes I need to make in the code? B ...

Unfulfilled commitment on bcrypt

I am currently facing an issue while trying to validate a user's password using bcryptjs. I have implemented a function that returns a Promise, but I am encountering an error when reaching the bycrypt.hash step - all I see is Promise { <pending> ...

Prevent the Swiper slider from autoplaying while a video is being played, and automatically move to the next slide once the video is paused or

<div class="swiper mySwiper"> <div class="swiper-wrapper"> <div class="swiper-slide"> <video-js id="6304418462001" class="overlayVideo" data-account= ...

React - callbackFromApp function is executing only one time when clicked

Whenever I click a button within my child React module, it is meant to increment the timer and then pass back the timer in minutes and total seconds to the parent component where it will be stored as state. The issue I am facing is that when I click the b ...

What is the reason behind Firefox failing to display a linear gradient when the background-size values are more than 255px?

I am working on creating a grid overlay using an absolutely positioned non-interactive div. My approach involves using the repeating-linear-gradient property as suggested by others for this purpose. The functionality works smoothly in Chrome, but I seem to ...

In JavaScript, the event.defaultPrevented property will never be set to true

I've been experimenting with events in my script, but I'm struggling to understand the functionality of event.preventDefault()/event.defaultPrevented: var e = new Event('test'); e.defaultPrevented; > false e.preventDefault(); e.d ...

Revamping this snippet - JavaScript with NodeJs

Currently working on a basic CRUD application, encountering an issue with obtaining the auto-incrementing value for the latest account in MongoDB. To provide more context, I've included the snippet below to achieve the following: 1) Conduct validati ...

Introducing Block Insert feature in React Draft-js - a powerful

How the Process Works: Upon hitting the spacebar, the Draft-JS editor queries the text content for a specific word. Subsequently, all instances of that word are enveloped in tags. The HTML is then converted back and the state of the Draft-JS editor is upd ...

Gathering the presently unfinished observables within a superior-level rxjs observable

As an illustration, let's consider a scenario where I have a timer that emits every 5 seconds and lasts for 10 seconds. By using the scan operator, I can create an observable that includes an array of all the inner observables emitted up until now: c ...