/    Sign up×
Community /Pin to ProfileBookmark

Hello,

I am working with a peice of Javascript I found online. This code will search, find and highlight the text when it is found. The problem is, you have to keep clicking SEARCH to find all of the text. I am fairly new to Javascript and can’t figure out what I need to add (or remove) from this script to get it to search, highlight and find ALL of the matching text on the page.

Any help would be great.
Thanks!
CODE:

[code]
<!–BEGIN SEARCH BOX –>

<div class=”search_box”>
<form action=”” id=”form2″>
<div>
<input type=”text” id=”search”>
<input type=”button” id=”submit_form” onclick=”checkInput()” value=”Submit”>
</div>
</form>
</div>

<!–END SEARCH BOX –>
<script>
function checkInput() {
var query = document.getElementById(‘search’).value;
window.find(query);
return true;
}
</script>
[/code]

to post a comment
JavaScript

10 Comments(s)

Copy linkTweet thisAlerts:
@NogDogNov 22.2021 — I added ... tags around your code block to aid readability here. Please be sure to use them going forward here. ;)
Copy linkTweet thisAlerts:
@SempervivumNov 22.2021 — I implemented a search feature some time ago and modified it. Now it highlights all of the text at once. Check if it meets your requirement.
``<i>
</i>&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;

&lt;head&gt;
&lt;meta charset="UTF-8"&gt;
&lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt;
&lt;title&gt;Search Document&lt;/title&gt;
&lt;style&gt;
.found {
background-color: lightblue !important;
}
&lt;/style&gt;

&lt;/head&gt;

&lt;body&gt;
&lt;label id="search-lbl" for="search-input"&gt;Search&lt;/label&gt;
&lt;input id="search-input"&gt;
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore
magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd
gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing
elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero
eos et
accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor
sit
amet. &lt;div&gt;Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore
et
dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet
clita
kasd
gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.&lt;/div&gt;

&lt;div&gt;Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie consequat, vel illum dolore eu
feugiat
nulla facilisis at vero eros et accumsan et iusto odio dignissim qui blandit praesent luptatum zzril delenit
augue
duis
dolore te feugait nulla facilisi. &lt;div&gt;Lorem ipsum dolor sit amet&lt;/div&gt;, consectetuer adipiscing elit, sed diam
nonummy nibh
euismod tincidunt ut laoreet dolore magna aliquam erat volutpat.&lt;/div&gt;

&lt;script&gt;
document.getElementById('search-lbl').addEventListener('click', searchIt);
function undoSearch(cls) {
// Ueber alle Fundstellen:
document.querySelectorAll('span.' + cls).forEach(item =&gt; {
// Elternelement ermitteln
const parent = item.parentNode;
// Textknoten mit Text des Elternelementes erzeugen
const newTxtNode = document.createTextNode(parent.textContent);
// ... und Elternelement damit ersetzen
parent.replaceWith(newTxtNode);
// Jetzt hat der Knoten wieder der ursprünglichen Zustand
});
}
function search(node, needle, cls) {
const regex = new RegExp('(' + needle + ')', 'ig');
node.childNodes.forEach(node =&gt; {
switch (node.nodeType) {
// Handelt es sich um einen Elementknoten?
case 1:
// Suche fortsetzen
search(node, needle, cls);
break;
// Handelt es sich um einen Textknoten?
case 3:
// Den Text heraus ziehen
const txt = node.textContent.trim();
// console.log(txt)
if (txt != '' &amp;&amp; txt.includes(needle)) {
// Um den gefundenen Text hervor zu heben, betten wir ihn ein
// span-Element ein, das wir dann geeignet mit CSS gestalten koennen.
// In einem Textknoten wird jedoch kein HTML interpretiert.
// Daher erzeugen wir ein neues span-Element und tragen dort den
// geaenderten Text ein.
let newEle = document.createElement('span');
newEle.innerHTML = txt.replace(regex, '&lt;span class="' + cls + '"&gt;$1&lt;/span&gt;')
node.replaceWith(newEle);
break;
}
}
});
}
let lastSearchStr = '',
foundElems,
idxSearch = 0;
// Die folgende Funktion wird durch das Suchformular aufgerufen
// und startet die Suche
function searchIt(event) {
const
idInput = event.target.getAttribute('for'),
needle = document.getElementById(idInput).value;
// event.preventDefault();
// Unterscheidet sich der Suchstring vom gespeicherten?
// D. h. handelt es sich um eine neue Suche?
if (needle != lastSearchStr) {
lastSearchStr = needle;
idxSearch = 0;
// Aenderungen am DOM von der vorigen Suche rueckgaengig machen
undoSearch('found');
// Suche starten
search(document.querySelector('body'), needle, 'found');
// Gefundene Element bereit stellen
foundElems = document.querySelectorAll('.found');
searchDone = true;
}
return false;
}

&lt;/script&gt;
&lt;/body&gt;

&lt;/html&gt;<i>
</i>
``

Unfortunately I coded this for a user in a german forum and therefore the remarks are german. Please ask if you don't understand how the code works. If required I would translate them to english.
Copy linkTweet thisAlerts:
@Caesar1010authorNov 22.2021 — @Sempervivum#1639741 Thank you - But the search should be able to go through the entire page, not just what is within the "search-input" ID.

Appreciate you taking the time to reply!
Copy linkTweet thisAlerts:
@SempervivumNov 22.2021 — >the search should be able to go through the entire page, not just what is within the "search-input" ID.

For me it does. I takes the value from the input and highlights every occurrence in the document.

Which browser are you using?
Copy linkTweet thisAlerts:
@Caesar1010authorNov 23.2021 — Using FireFox v94.0.2

Thanks.
Copy linkTweet thisAlerts:
@SempervivumNov 23.2021 — I tried firefox and it works fine. After searching the screen looks like this:

![](https://webentwicklung.ulrichbangert.de/webdev/search.png)
Copy linkTweet thisAlerts:
@Caesar1010authorNov 23.2021 — Using FireFox v94.0.2

I should be able to take your code and remove the "orem ipsum dolor sit amet... " section which just leaves me with the
``<i>
</i>
`</CODE>
&lt;label id="search-lbl" for="search-input"&gt;Search&lt;/label&gt;<br/>
&lt;input id="search-input"&gt;<br/>
&lt;script&gt;<br/>
document.getElementById('search-lbl').addEventListener('click', searchIt);<br/>
function undoSearch(cls) {<br/>
// Ueber alle Fundstellen:<br/>
document.querySelectorAll('span.' + cls).forEach(item =&gt; {<br/>
// Elternelement ermitteln<br/>
const parent = item.parentNode;<br/>
// Textknoten mit Text des Elternelementes erzeugen<br/>
const newTxtNode = document.createTextNode(parent.textContent);<br/>
// ... und Elternelement damit ersetzen<br/>
parent.replaceWith(newTxtNode);<br/>
// Jetzt hat der Knoten wieder der ursprünglichen Zustand<br/>
});<br/>
}<br/>
function search(node, needle, cls) {<br/>
const regex = new RegExp('(' + needle + ')', 'ig');<br/>
node.childNodes.forEach(node =&gt; {<br/>
switch (node.nodeType) {<br/>
// Handelt es sich um einen Elementknoten?<br/>
case 1:<br/>
// Suche fortsetzen<br/>
search(node, needle, cls);<br/>
break;<br/>
// Handelt es sich um einen Textknoten?<br/>
case 3:<br/>
// Den Text heraus ziehen<br/>
const txt = node.textContent.trim();<br/>
// console.log(txt)<br/>
if (txt != '' &amp;&amp; txt.includes(needle)) {<br/>
// Um den gefundenen Text hervor zu heben, betten wir ihn ein<br/>
// span-Element ein, das wir dann geeignet mit CSS gestalten koennen.<br/>
// In einem Textknoten wird jedoch kein HTML interpretiert.<br/>
// Daher erzeugen wir ein neues span-Element und tragen dort den<br/>
// geaenderten Text ein.<br/>
let newEle = document.createElement('span');<br/>
newEle.innerHTML = txt.replace(regex, '&lt;span class="' + cls + '"&gt;$1&lt;/span&gt;')<br/>
node.replaceWith(newEle);<br/>
break;<br/>
}<br/>
}<br/>
});<br/>
}<br/>
let lastSearchStr = '',<br/>
foundElems,<br/>
idxSearch = 0;<br/>
// Die folgende Funktion wird durch das Suchformular aufgerufen<br/>
// und startet die Suche<br/>
function searchIt(event) {<br/>
const<br/>
idInput = event.target.getAttribute('for'),<br/>
needle = document.getElementById(idInput).value;<br/>
// event.preventDefault();<br/>
// Unterscheidet sich der Suchstring vom gespeicherten?<br/>
// D. h. handelt es sich um eine neue Suche?<br/>
if (needle != lastSearchStr) {<br/>
lastSearchStr = needle;<br/>
idxSearch = 0;<br/>
// Aenderungen am DOM von der vorigen Suche rueckgaengig machen<br/>
undoSearch('found');<br/>
// Suche starten<br/>
search(document.querySelector('body'), needle, 'found');<br/>
// Gefundene Element bereit stellen<br/>
foundElems = document.querySelectorAll('.found');<br/>
searchDone = true;<br/>
}<br/>
return false;<br/>
}

<i> </i><CODE>&lt;/script&gt;</CODE>
&lt;/body&gt;

&lt;/html&gt;
<CODE>
`<i>
</i>
``


Is that correct?


Thanks.
Copy linkTweet thisAlerts:
@SempervivumNov 23.2021 — Yes, replace the lorem-ipsum-content by your own one.
Copy linkTweet thisAlerts:
@Caesar1010authorNov 23.2021 — @Sempervivum#1639790 Thank you.
Copy linkTweet thisAlerts:
@SempervivumNov 23.2021 — BTW: You used triple backticks two time at the beginning and the end of your code:
&lt;/html&gt;
``<span><code>&lt;i&gt;
&lt;/i&gt;
</code></span>`<span><code>
</CODE>
Just use only one set and the formatting will be correct:
<CODE>&amp;lt;/html&amp;gt;
</code></span>``
×

Success!

Help @Caesar1010 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 3.28,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,

tipper: Anonymous,
tipped: article
amount: 10 SATS,
)...