0

Here is my html

<input type="text" />
<div>
  <p>Apple</p>
  <p>Peach</p>
  <p>Bannana</p>
  <p>Tomato</p>
</div>

And my jQuery code yet

var items = $("div").find("p").text();

console.log(items);

How can I highlight each character inside div p that matches value in input? Let's say that users write down in input character "a". Page should look like this, even A character in apple should be bold.

Apple

Peach

Bannana

Tomato

here is codepen as well

Karolina Ticha
  • 531
  • 4
  • 19
  • Please include attempted solutions, why they didn't work, and the expected results. That would really helps us to figure out the issue with your code. Thanks! – palaѕн Aug 15 '16 at 08:28
  • Man, there are tons of answers here on SO. You may have a look at [mark.js](https://markjs.io) – dude Aug 15 '16 at 15:42

1 Answers1

0

One option is:

// Borrowed from:
// http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript#answer-3561711
function escapeRegex(str) {
   return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}

var items = $("div").find("p");

$('input').on('keyup', function() {
   var reg = new RegExp('(' + escapeRegex(this.value) + ')', 'gi');
   items.html(function() {
      return this.textContent.replace(reg, "<b>$1</b>");
   });
});

Note that above answer assumes (based on the posted markup) that p elements only have text contents. If the p elements have child elements then another option should be considered as the code snippet can have side effects and create invalid markup.

https://jsfiddle.net/xbqetxdo/

Ram
  • 143,282
  • 16
  • 168
  • 197
  • Using innerHTML is evil, will destroy events and triggers regeneration of the DOM – dude Aug 15 '16 at 15:43
  • @dude Yes, in some cases, modifying `innerHTML` property of the `body` element, as an example, is, of course, a terrible idea. But the above answer somehow only modifies the _textContent_ of an element, it assumes (based on the posted markup) that `p` elements only have text contents and you can't bind event handlers to text nodes after all, right? So you won't lose any event handlers in this case, also this question is not related to event bindings and for dynamic elements one can use event delegation. – Ram Aug 15 '16 at 17:02