0

I'm writing a simple script for detecting changes in the DOM, and then performing some actions.

I want to achieve something like this:

$('body').on('DOMNodeInserted', '#entry', function() {
// check if inserted element contains text, then run function
})

What is the simplest way of search text on the inserted DOM node?

  • 2
    Possible duplicate of [Jquery: Checking to see if div contains text, then action](http://stackoverflow.com/questions/902597/jquery-checking-to-see-if-div-contains-text-then-action) – Banzay Feb 06 '17 at 16:54
  • I would imagine a simple indexOf would do the trick: `console.log(insertedElement.val().indexOf("my text to check") > -1)` – mhodges Feb 06 '17 at 16:54

1 Answers1

1

You can use the event.target property of the passed in event object within the handler and perform a check using methods such as indexOf() or similar to determine if the text you are looking for is present.

$(document).on('DOMNodeInserted', function(e) {
    var $targetElement = $(e.target);

    if($targetElement.text().indexOf('Test') > -1) {
        console.log('foo');
    }
});

Here is a fiddle demonstrating a simple check of inserted elements' text using text() and indexOf().

Alexander Staroselsky
  • 37,209
  • 15
  • 79
  • 91