Ways to iterate over all div elements containing a certain class using JavaScript

I am currently working on creating a search functionality for an FAQ page that will filter out results that do not contain the keywords entered by the user. Right now, the search function only highlights the keywords, and I have assigned divs with the class "faq-question" for each question. My goal is to iterate through each div with the class "faq-question", check if the searched keyword (marked with the "mark" tag) is present, and then change the background color of that section accordingly. However, my current code is highlighting all the divs with the class "faq-question" instead of just those containing the <mark> tag. How can I resolve this issue?

HTML

<input type="text" id="keywords" placeholder="Search on the page..."></input>
<div class="faq-question"><h4>What is Lorem Ipsum?</h4>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.<p></div>
<div class="faq-question"><h4>Why do we use it?</h4>
<p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.</p></div>

Javascript:

//Hide unrelated search results
var question = document.getElementsByClassName("faq-question");
var keyword = document.querySelector("mark");


for(x = 0; x < question.length; x++) {
    if(typeof(keyword) != 'undefined' && keyword != null){
        question[x].style.backgroundColor = "#FFFF00";
        console.log("shown");
    } else {
        question[x].style.backgroundColor = "#FFFFFF";
        console.log("hidden");
    }
}

Edit: The <mark> tag is a dynamic value. To clarify, if you enter "lorem" in the

<input id="keywords">
, the HTML will change to

<h4>What is <mark>Lorem</mark> Ipsum?</h4>

...and so forth. In this case, I am using the <mark> tag to determine if the div contains the matching keywords that the user searched for.

Answer №1

Simply a minor spelling error. You defined the variable as questions, so inside the for loop it should be questions not question

The corrected code would be

<input type="text" id="keywords" placeholder="Search on the page..."></input>
<div class="faq-question"><h4>What is <mark>Lorem Ipsum?<mark></h4>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.<p></div>
<div class="faq-question"><h4>Why do we use it?</h4>
<p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.</p></div>

    var questions = document.getElementsByClassName("faq-question");


    for(x = 0; x < questions.length; x++) {
    if(questions[x].getElementsByTagName('mark').length){
        questions[x].style.backgroundColor = "#FFFF00";
        console.log("shown");
    } else {
        questions[x].style.backgroundColor = "#FFFFFF";
        console.log("hidden");
    }
}

Answer №2

When selecting various questions, make sure to verify if the element is a child. If it is indeed a child, then toggle a specific class.

document.querySelectorAll(".faq-question").forEach(function(elem) {
  const hasMarks = elem.querySelectorAll("mark").length > 0;
  elem.classList.toggle("hasMatch", hasMarks);
});
.hasMatch {
  background-color: lime;
}
<div class="faq-question">
  <h4>What is Lorem Ipsum?</h4>
  <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.
    <p>
</div>
<div class="faq-question">
  <h4>Why do we use it?</h4>
  <p>It is a long established <mark>fact</mark> that a reader will be distracted by the readable content of a page when looking at its layout.</p>
</div>

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

Learn how to implement code splitting in a React application with webpack by exporting components using the syntax "export * from '...'"

In my React app, I recently implemented code splitting which has been working well. However, when analyzing the bundle size, I noticed an issue with how my components folder is loaded in the initial chunk. It includes all components, even those that are on ...

AJAX-powered Form Validation

I am in the process of creating a login form that includes three input fields: one for entering a username, another for entering a password, and a submit button to log in. Currently, I am utilizing AJAX to validate the login information directly on the cl ...

What is the proper way to place a newly added element using absolute positioning?

Currently, I am in the process of developing a tooltip feature. This function involves adding a div with tooltip text inside it to the element that is clicked. However, I am facing a challenge in positioning this element above the clicked element every tim ...

The PayPal JavaScript SDK button triggers a blank window with a #blocked URL when used in a Django template, but does not have the same issue

I've been grappling with an issue while trying to incorporate PayPal buttons into my Django website. Every time I attempt to do so, the PayPal popup window shows up as about:blank#blocked. In the console, I can see the following error: popup_open_erro ...

Ways to utilize a single HTML page for various URLs while changing one variable value based on the queried URL

My current HTML page structure looks like this: <body ng-controller="DashboardDisplay" onload="submit()"> <div class="container-fluid" > {{scope.arr}} </div> </body> <script> var myApp = angular.module(&apos ...

The filter() and some() functions are not producing the anticipated output

Currently, I am in the process of developing a filtering mechanism to sift through a dataset obtained from an API. The array that requires filtering contains objects with various parameters, but my aim is to filter based only on specific parameters. For ...

JavaScript 3D Arrays

Is there a way to create a 3D array similar to runes['red'][0]['test']? If so, how can I accomplish this? var runes = {} runes['red'] = [ 'test': ['loh'] ] runes['blue'] = {} runes[&apo ...

What is the best way to change messages into utf-8 format?

I'm currently working on a project involving sockets where the client is in C and the server is in JavaScript. However, when I attempt to send data from one to the other, I encounter the error ECONNRESET. From my research, it seems that this issue ari ...

Can a stack method be utilized to create a HTML tag checker?

I've been developing a project to create an HTML validation tool based on stacks, but I've encountered some issues. The main objective is to verify if the HTML tags are correctly nested and closed. However, there seem to be discrepancies in the r ...

Setting the rotation position in JQuery prior to initiating the animation

Perhaps I could phrase my query differently as How can I rotate an image in JQuery from a starting position other than 0 degrees. I am attempting to animate the rotation of an image from -50deg to 0deg. However, regardless of what I do, JQuery seems to al ...

Modify the fixed div's class when the user scrolls past a certain section

My page includes a fixed menu with various sections, each assigned a specific class name using data attributes (e.g. data-menu="black"). I want the fixed menu to change its class based on the section that is currently underneath it as the user scrolls. Y ...

AmazingStew 4 - How to substitute anchor element with its text

My document contains HTML content and I am looking to replace all anchor tags with their respective texts using BeautifulSoup. Here is the input: html = '''They are also much more fuel-efficient than <a href="http://someurl.com">rock ...

Using JSON files in React applications is essential for accessing and displaying static data. Let's

If I want to refer to a file locally in my JS code instead of on a remote server, how can I do that? I know the file needs to be in the public folder, but I'm unsure how to reference it in the JavaScript provided above. class App extends Component { c ...

The Masonry Grid is leaving empty spaces unfilled

I've been experimenting with Sveltekit and SCSS to create a Masonry grid. However, I'm facing an issue where the items in my grid are not filling in the empty space as expected. Instead, they seem to be following the size of the largest image, le ...

AngularJS Error: $interpolate:interr - Encounter with Interpolation Error

Having some trouble embedding a YouTube video into my website using AngularJS. Keep receiving this pesky error: Error: $interpolate:interr Interpolation Error Any idea why this error is popping up and how I can resolve it? Just trying to add the video... ...

Ways to avoid margin overflow in CSS

I am facing an issue with the code below where the last row overflows the parent container. I have tried using overflow: auto; to fix it, but that just adds scrollbars. Any suggestions on how to prevent the overflow? <link rel="stylesheet" href="http ...

What are some strategies for establishing communication between sibling components in Vue?

Currently, my Vue app has a structure that includes a "blackout" component for displaying modals and a router-view for various sub-menus. These components are siblings at the same level. <blackout v-if="this.popup.currentPopup"></blacko ...

I possess a pair of UI tabs. Whenever a button located outside the tab is clicked, I am required to activate a distinct tab

As a beginner in Javascript, I recently encountered an issue with a UI tab element that contains two tabs. My goal is to create a button that, when clicked, will scroll up and activate the second tab. <style> .tab-container { overflow-x: ...

Struggling to align elements vertically and horizontally using Bootstrap in an HTML file

Here is the code snippet that I have written: .box { background-color: red; } .container { height: 50vh; background-color: blue; } <!DOCTYPE html> <html lang="en"> <head> ...

Receiving the latest global variable in JavaScript using jQuery

I keep receiving undefined type for: $(".ui-slider-handle").attr("title", '"'+current+'"'); Even though I can successfully alert the updated value of current on line 29, it seems to not be working with .at ...