Find div elements that contain the designated text

I am looking to implement a search function on my website that will filter out divs that do not match the criteria. The current div list is structured as follows:

<body>
<div class='subjects'>
    <div id='subject'>soccer</div>
    <div id='subject'>dancing</div>
    <div id='subject'>soap</div>
</div>
</body>

For example, if I search for 's', it should only display the soccer div and not show the dancing div. Likewise, searching for 'soa' should only show the soap div without removing any divs.

I am new to implementing search functionality, so any guidance or tips would be greatly appreciated.

PS: The tags I provided indicate the available languages, and if an extension is needed, that is not a problem.

Answer №1

If you want to achieve this, you can utilize the power of jQuery. Here is an example:

HTML:

<div class='categories'>
    <div>football</div>
    <div>ballet</div>
    <div>TV shows</div>
</div>

<input type="text" id='search' />

jQuery:

$('#search').on('input', function(){
    var text = $(this).val();
    $('.categories div').show();    
    $('.categories div:not(:contains(' + text + '))').hide();
});

Working Example

Answer №2

In the realm of Pure Object-Oriented JavaScript (POJS) and exclusively focusing on modern browsers that support ECMA5 & HTML5, specifically IE10+

CSS

.hide {
    display: none;
}

HTML

<input id="search"></input>
<div class="subjects">
    <div class="subject">soccer</div>
    <div class="subject">dancing</div>
    <div class="subject">soap</div>
</div>

Javascript

document.getElementById("search").addEventListener("keyup", function (evt) {
    [].forEach.call(document.querySelectorAll(".subjects .subject"), function (subject) {
        if (subject.textContent.indexOf(evt.target.value) === -1) {
            subject.classList.add("hide");
        } else {
            subject.classList.remove("hide");
        }
    });
}, false);

jsfiddle

Exploring POJS with a cross-browser approach required supporting IE5.5+

Javascript

function walkTheDOM(node, func) {
    func(node);
    node = node.firstChild;
    while (node) {
        walkTheDOM(node, func);
        node = node.nextSibling;
    }
}

function classNameToArray(className) {
    return className.split(/ +/);
}

function getElementsByClassName(node, className) {
    var array = [],
        elements = node.getElementsByTagName("*"),
        elementsLength = elements.length,
        i = 0,
        element,
        classNames,
        classNamesLength,
        x;

    while (i < elementsLength) {
        element = elements[i];
        classNames = classNameToArray(element.className);
        for (x = 0, classNamesLength = classNames.length; x < classNamesLength; x += 1) {
            if (classNames[x] === className) {
                array.push(element);
                break;
            }
        }

        i += 1;
    }

    return array;
}

document.getElementById("search").onkeyup = function (evt) {
    var e = evt || window.event,
        target = e.target || e.srcElement,
        subjects = getElementsByClassName(document, "subjects"),
        subject = [],
        classnames,
        classNamesLength,
        classIndex,
        element,
        length,
        index,
        text;

    for (index = 0, length = subjects.length; index < length; index += 1) {
        subject = subject.concat(getElementsByClassName(subjects[index], "subject"));
    }

    for (index = 0, length = subject.length; index < length; index += 1) {
        text = "";
        element = subject[index];
        walkTheDOM(element, function (currentNode) {
            if (currentNode.nodeType === 3) {
                text += currentNode.nodeValue;
            }
        });

        classNames = classNameToArray(element.className);
        for (classIndex = classNames.length - 1; classIndex >= 0; classIndex -= 1) {
            if (classNames[classIndex] === "hide") {
                classNames.splice(classIndex, 1);
            }
        }

        if (text.indexOf(target.value) === -1) {
            classNames.push("hide");
        }

        element.className = classNames.join(" ");
    }
};

jsfiddle

Alternatively, utilizing jQuery with compatibility for IE6+ or IE9+ depending on the jQuery version

Javascript

$("#search").keyup(function (evt) {
    var subject = $(".subjects .subject");

    subject.removeClass("hide");
    subject.each(function (index, element) {
        var $element = $(element);

        if ($element.text().indexOf(evt.target.value) === -1) {
            $element.addClass("hide");
        }
    });
});

jsfiddle

All these illustrations incorporate CSS for styling the divs, offering flexibility to customize styling beyond mere showing/hiding such as highlighting or applying borders.

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

Upon transitioning from typescript to javascript

I attempted to clarify my confusion about TypeScript, but I'm still struggling to explain it well. From my understanding, TypeScript is a strict syntactical superset of JavaScript that enhances our code by allowing us to use different types to define ...

Seamless transition animation using jquery

I'm attempting to create a smoother transition when the button is clicked, but so far it's not working as expected. I tried using $slideToggle, but I may have implemented it incorrectly. <button class="btn btn-warning" id="btn-m ...

Creating dynamic fields for an ExtJS chart

Can chart axes be customized using setFields? I looked through the documentation for a method called setFields, but couldn't find one. While I was able to use setTitle on an axes, setting the field proved to be more challenging. I have a variable ca ...

What methods can I use to identify the selector for this element?

After pinpointing the specific element in Google Chrome using inspect element, what kind of path or syntax should I use to apply a method to this element? The hierarchy for the element is outlined below: html body div#contentDiv div#searchFormDiv ...

Changing the 'null' string to null in JavaScript

Within an array of objects, some keys have a value of "null" as a string that I want to convert to null. Here is the code I tried: let obj = [{ "fundcode": "DE", "fundname": "Defens", ...

Exploring all hidden input values by utilizing $.each

I'm trying to perform a specific action with each hidden input value, and in order to do so I wrote the following JavaScript code utilizing jQuery. $.each($("input[type='hidden']"), function (index, value) { alert(value.val()); }); Unf ...

`Balance in structure`

Having trouble with CSS. I would like to make this form symmetrical. Buttons should be in one column, textfields in another, and the question mark should also have its own column. Apologies if the ticket structure is not perfect, this is only my second on ...

How can I monitor an input field that already has a value in Vue?

My current setup includes an email input and a watcher that verifies if the input is valid or not. The issue I'm facing is that the watch event only triggers when something new is typed into the email field. This means that if the existing value in th ...

Whenever I try to run npm start, my webpack is not able to locate my index.html page

Recently delving into the world of node.js and its packages, I initiated by executing npm init to lay out the package.json structure shown below: { "name": "test", "version": "1.0.0", "description": & ...

Horizontal Scrolling Menu for Dynamic Page Navigation

My goal was to create a smooth-scrolling one-page website that scrolls horizontally. One feature I wanted was a menu that smoothly slides into view whenever a new page is in focus along with the horizontal scrolling. I found an example of a scrolling scr ...

Retrieving data from a server using the GET method with parameters through axios in a React Native application

As someone new to Web requests, I have encountered a challenge that seems simple but has proven difficult for me. Despite searching the web, I am struggling to get a working response. When I input the URL 'http://www.test.com/callservice.php?action=s ...

Enable the onlclick event to trigger only a single

I am looking for a way to avoid adding a long list of option elements multiple times to a select list when clicking on it. How can I achieve this? $("#skiresort").click(function(){ $("#skiresort").load("/v3/inc/review.php"); }); ...

Initial Search Function in a MEAN Stack Site

Working on a MEAN stack application for a school project, I'm almost done but struggling to add search functionality. Creating a search feature for ICD-10 codes in a medical app is my goal. Just need a basic search of symptoms or codes that displays ...

Assurances for a function devoid of any output information

Currently, I am in the process of unraveling a complex web of callback-based code for node.js, and it appears that promises may be the solution due to numerous asynchronous database operations. Particularly, my focus is on utilizing Bluebird. I have reach ...

Show the information in an array that corresponds to the selected option in a dropdown menu

I have an array with country data and I want to display specific information based on a selected option from a dropdown menu. The 'making_calls' value should be displayed in the .price-call paragraph, and the 'sending_texts' value in t ...

Why is it important to incorporate an inner function in order to return to the outer function?

Can you explain the distinction between these two functions, bind_1 and bind_2? function bind_1(f, o) { if (f.bind) return f.bind(o); else return function() { return f.apply(o. arguments); }; } function bind_2(f, o) { if (f. ...

I need help with creating an AJAX JSON call using Angular. Let me share the JavaScript function that I currently have

When a button is clicked, the function below is called. It retrieves data from a JSON file and stores it if a success message is received. Here is a screenshot of the returned data. My JavaScript function is working correctly, but I am new to Angular and l ...

Changing the 'badge' to 'panel' within the UI framework of 'ant design' has been set

Can the Badge be placed next to 'Info' in a Panel using ant design? https://i.sstatic.net/Lldc7.png View Code <div> <Collapse> <Panel header="Info" key="1"> <Badge count={4} style={{ b ...

Trouble with Vuex Store: Changes to table values not reflected in store

I've been tackling a table project using Quasar framework's Q-Popup-edit and Vuex Store. The data populates correctly initially. However, any changes made on the table do not seem to persist and revert back to their original values. Here is a s ...

Guide on accessing text content from a sibling div element using jQuery

There are several divs arranged on a page as shown below. If a user clicks a link within the UL .list-links, I want to capture the content inside: <span class="asa_portlet_title">Title here</span> and store it in a variable. I have attempted ...