keyword search in page
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.highlight{ | |
background-color:yellow; | |
} | |
.hide{ | |
display: none; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<input id="sample_word" placeholder="keyword" type="text"> | |
<div id="sample_area"> | |
<div class="sample_part"> | |
<h3>サンプルテキスト</h3> | |
<p>サンプルテキストサンプルテキストサンプルテキストサンプルテキストサンプルテキストサンプルテキスト</p> | |
</div> | |
<div class="sample_part"> | |
<h3>サンプルテキスト</h3> | |
<p>サンプルテキストサンプルテキストサンプルテキストサンプルテキストサンプルテキストサンプルテキスト</p> | |
</div> | |
<div class="sample_part"> | |
<h3>サンプルテキスト</h3> | |
<p>サンプルテキストサンプルテキストサンプルテキストサンプルテキストサンプルテキストサンプルテキスト</p> | |
</div> | |
<div class="sample_part"> | |
<h3>sample text</h3> | |
<p>sample textsample textsample textsample textsample textsample textsample text</p> | |
</div> | |
</div> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const yougo_area = document.getElementById('sample_area'); | |
const yougo_parts = document.getElementsByClassName('sample_part'); | |
const input = document.getElementById('sample_word'); | |
input.addEventListener('input',()=>{ | |
reset(); | |
const sword = input.value; | |
if(sword==''){return} | |
const regexp = new RegExp(`(?<=>)[^<>]*?(${sword})[^<>]*?(?=<)`,'gi'); | |
const regexp2 = new RegExp(sword,'gi'); | |
[...yougo_parts].forEach(part=>{ | |
if(part.textContent.indexOf(sword)==-1){ | |
part.classList.add('hide'); | |
}else{ | |
part.innerHTML=part.innerHTML.replace(regexp,function(){ | |
return arguments[0].replace(regexp2,`<span class="highlight">${sword}</span>`); | |
}); | |
} | |
}); | |
}); | |
function reset(){ | |
console.log('reset'); | |
[...document.getElementsByClassName('highlight')].forEach(el=>{ | |
el.outerHTML=el.textContent; | |
}); | |
[...document.getElementsByClassName('hide')].forEach(el=>{ | |
el.classList.remove('hide'); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment