最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Search for divs that contain specified text - Stack Overflow

programmeradmin1浏览0评论

I want to make a search function on my website, where I search for divs (and leave out the divs which didn't meet what I searched for. The div list looks like this:

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

For instance, when I search for the 's' it doesn't show the div which the dancing inside and when you write 'soa' it shows soap only (not removing divs not matching, just don't show them).

I really have no experience with searching stuff, so all information is wele.

ps. the tags I added are the languages that are available, if I need an extension: that's no problem.

I want to make a search function on my website, where I search for divs (and leave out the divs which didn't meet what I searched for. The div list looks like this:

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

For instance, when I search for the 's' it doesn't show the div which the dancing inside and when you write 'soa' it shows soap only (not removing divs not matching, just don't show them).

I really have no experience with searching stuff, so all information is wele.

ps. the tags I added are the languages that are available, if I need an extension: that's no problem.

Share Improve this question edited Sep 29, 2013 at 15:42 Xotic750 23.5k8 gold badges59 silver badges81 bronze badges asked Sep 29, 2013 at 13:23 PMintPMint 2462 silver badges13 bronze badges 2
  • id='subject' 3 place change them to class :) – Anobik Commented Sep 29, 2013 at 13:32
  • 1 You can't have multiple instances of an id. – Popsyjunior Commented Sep 29, 2013 at 13:33
Add a ment  | 

2 Answers 2

Reset to default 12

You can use jQuery to do it, something like this:

HTML:

<div class='subjects'>
    <div>soccer</div>
    <div>dancing</div>
    <div>soap</div>
</div>

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

jQuery:

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

Fiddle

In POJS and only caring about modern browsers (supporting ECMA5 & HTML5, 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

In POJS and cross-browser required (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

Or in jQuery (IE6+ or IE9+ depends on 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 of these examples use CSS to style the divs, so it is very easy to change your styling, if you don't want to just show/hide but maybe highlight or place a border.

发布评论

评论列表(0)

  1. 暂无评论