Why isn't my search function fully scanning all tag elements in Bootstrap and JavaScript?

As a beginner, I am currently on my second project involving Bootstrap and JS. For this project, I have created a search form and multiple cards with two paragraphs each.

<div class="container">
    <div class="row justify-content-center my-5">
        <input class="form-control col-xs-12 col-lg-10 col-sm-8" id="myInput" type="text" onkeyup="myFunction()" placeholder="Search">
        <button class="btn btn-outline ml-2 my-xs-2 col-xs-8 " style="font-family: Arial, Helvetica, sans-serif; font-weight: 700;">SEARCH</button>
    </div>
</div>
<div class="container">
    <ul class="row" id="myList" style="list-style-type: none;">
        <li class="card mb-4 box-shadow"><p>Adele</p><p>2001</p></li>
        <li class="card mb-4 box-shadow"><p>Agnes</p><p>1980</p></li>

        <li class="card mb-4 box-shadow"><p>Billy</p><p>2010</p></li>
        <li class="card mb-4 box-shadow"><p>Bob</p><p>1530</p></li>

        <li class="card mb-4 box-shadow"><p>Calvin</p></li>
        <li class="card mb-4 box-shadow"><p>Christina</p></li>
        <li class="card mb-4 box-shadow"><p>Cindy</p></li>
    </ul>
</div>

Below is my script:

function myFunction() {
      var input, filter, ul, li, p, i, txtValue;
      input = document.getElementById('myInput');
      filter = input.value.toUpperCase();
      ul = document.getElementById("myList");
      li = ul.getElementsByTagName('li');
    
      for (i = 0; i < li.length; i++) {
        p = li[i].getElementsByTagName("p")[0];
        txtValue = p.textContent || p.innerText;
        if (txtValue.toUpperCase().indexOf(filter) > -1) {
          li[i].style.display = "";
        } else {
          li[i].style.display = "none";
        }
      }
    }

While searching by name works fine, entering the year does not yield results. The issue seems to be related to how the script handles the second paragraph. Any suggestions on how to modify the script in order to address this problem?

Answer №1

After Rich DeBourke's insight, it became clear that the issue was with utilizing the 0 index in this particular line:

p = li[i].getElementsByTagName("p")[0];

I propose using a different approach:

function myFunction() {
    const input = document.getElementById("myInput");
    const inputValue = input.value.toUpperCase();

    const ul = document.getElementById("myList");
    const lis = ul.getElementsByTagName("li");

    for (let li of lis) {
        const [pName, pYear] = li.getElementsByTagName("p");

        // In this scenario, we are assuming that the name's paragraph will always exist, while the year may not
        const textPName = pName.innerText.toUpperCase();
        const textPYear = pYear?.innerText.toUpperCase();

        if (
            textPName.startsWith(inputValue) ||
            (textPYear && textPYear.startsWith(inputValue))
        ) {
            li.style.display = "block";
        } else {
            li.style.display = "none";
        }
    }
}

Some key benefits of this alternative method include:

  • Variables are defined closer to their usage and have names directly related to their purpose within the function.
  • We prioritize using const over var where applicable.
  • We opt for a for/of loop instead of a traditional for loop since we do not require the index.
  • The array of li elements is deconstructed into appropriately named variables for immediate use.
  • We account for edge cases in our conditional statement (such as the possibility of the year not being present).
  • When retrieving element content, innerText is utilized as a simpler option, and the default display value of block is set in our if statement rather than an empty string.

I hope this solution proves helpful!

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

Determine the dimensions of a div element with overflow property and utilize the information to establish a boundary for the scrollbar

While this may seem like a straightforward question, I'm struggling to find a solution. Consider a div with an overflow property set, causing a scroll bar to appear when the text added is larger than its dimensions. You can see an example of this her ...

Utilizing a Custom Hook for Updating Components in useEffect

I am facing an issue with the following code snippet: function checklogin(callback) { if (!state.user.authenticated) pushhistory("/accounts/login", function(){teamhome2_message();}); else callback(); } // TRYING TO CONVERT IT INTO ...

Notification within the conditional statement in React JS

I am working on validating phone number input within a React JS component using an if/else statement. If the user enters letters instead of numbers, I want to display a message saying "please check phone number". While I have been able to create a function ...

I am unable to achieve negative X degree rotation of the image while using mousemove to rotate it

I need assistance with moving a picture in 3D. I want the offsetX of the mouse to be positive when it's past half of the picture, and negative otherwise. How can I achieve this effect for rotation degrees? This is what I have tried: $('#img ...

acquire information from a variable using angularjs

Given the following variable: var exampleVar = {"id": 0, "Nodeid": 1234, "title":"abc"}; I am looking to retrieve the Nodeid value from the above and save it in a new variable. The desired output should be: var newNodeID = 1234; ...

Using SOAP in a JavaScript-exclusive setting

I'm looking into utilizing SOAP as the backend services to supply data for my application. My query pertains to the feasibility of implementing this with just a JavaScript framework like Ember or Angular, without utilizing server-side languages such ...

Is there a way to retrieve the data attribute value from a button that has been clicked?

Is there a way to retrieve the data attribute value of a clicked button? I need this information for handling an ajax form submission. Any suggestions on how to achieve that? Here is an example of my button (there are multiple buttons corresponding to dif ...

Embedding HTML code in JavaScript

I am in the process of developing a karaoke-style website where I aim to incorporate HTML elements along with text. My intention is to introduce a break tag that will display certain lyrics on a separate page. You can access the codepen for this project h ...

There seems to be a problem retrieving the JSON file

My JavaScript file is designed to fetch a JSON file and execute a function if successful. If there's an error, it should display an alert window with the message "error". However, despite checking the syntax, I keep receiving an error alert every time ...

NodeJs Classes TypeError: Unable to access 'name' property as it is undefined

I am currently developing a useful API using Node.js. In order to organize my code effectively, I have created a UserController class where I plan to include all the necessary methods. One thing I am struggling with is how to utilize a variable that I set ...

Identifying a specific item within an array

Can someone guide me on how to manipulate a specific object within an array of objects? For example: var myArray = [ {id: 1}, {id: 2}, {id: 3}, {id: 4} ] // Initial state with the 'number' set as an array state = { number: [] } // A functio ...

How do you modify the color of the highlighted text using JavaScript?

I am currently using the Chrome browser. My background is blue and the text color is white. Issue: When I try to copy and paste the text into Word, it becomes invisible due to its color. Is there a JavaScript solution to change the text color when selec ...

Obtain decrypted information from the token

I am facing difficulty in retrieving decrypted user data for the current user. Every time a user logs in, they receive a token. After logging in, I can take a photo and send it to the server. Looking at my code, you can see that this request requires a to ...

Meteor twilio SMS feature not functioning properly

I'm currently using the Twilio node for sending SMS, but I've encountered an error: sendSms is not defined Within my server folder, here is the Twilio file I have: import twilio from "twilio"; sms = { accountSid: "xxxxxxxxxxxxxxxxxxxxxxx ...

Enable direct download from external servers

I'm in search of a way to prompt a download (by right-clicking and selecting "save as") for both mp4 and flv files. The challenge is that these files are not hosted on my server, they are direct links from external websites. I have tried using .htacce ...

Ways to eliminate the dotted line from the image map in Internet Explorer 11

Below you will find the code I am working with: <img alt="Testing 2015" border="0" src="images/Test-2015.jpg" usemap="#Map" /> <p><map name="Map"><area coords="790,100,653,135" href="http://www.google.com/" shape="rect" style="cursor ...

What is the best way to transfer a list from aspx to javascript?

When populating a table by looping through a list, I aim to pass a row of data to my JavaScript code. If that's not an option, I'd like to pass the list and the ID number for the specific row. How can I achieve this? <%foreach(var item in Mod ...

What about connecting mapStateToProps with a specific ID?

Currently, I have a basic function that fetches all Elements const mapStateToProps = ({elements}) => { return { elements: getElementsByKeyName(elements, 'visibleElements'), }; }; I want to modify it to something like this c ...

Are web components capable of managing changes in CSS (maybe through cssChangedCallback)?

Is there a way to control the application of CSS to a web component similar to using attributes through attributeChangedCallback. I am currently developing a couple of web components that could benefit from being styled with CSS classes. However, I requir ...

Calculating the sum of table columns with the help of knockout.js

Is there a way to calculate the table columns using knockout.js? I am familiar with jQuery but new to knockout.js and unsure how to approach this. Instead of generating the table data using JSON, I would like to directly create it in the HTML table itself. ...