Constantly check an html element for a specific value

Constantly check an html element for a specific value
0

#1

Okay, the plain-language description of what I want to do is “Watch that html element, and if its text is ever exactly equal to , alert(_).” Is there an easy way to do that? There’s jQuery .change(), but that’s only for input elements, and I’d like something for an ordinary div or h3.


#2

I don’t know a way to do that, but how is the element going to change?


#4

Check out the contenteditable attribute for DOM Elements:

Very useful for creating an in-place editor for values (think editing data presented in a table without using a modal popup)

MDN Editable Content

Just brainstorming, but that seems a likely situation in which you would listen for the event P1xtr referred to.

Another might be a piece of your code needing to watch for changes in another part of the DOM, outside of it’s scope or control …


#5

There must be an event that changes the element text, so ideally you do it by hooking into that. It has to be taking input from somewhere, so you check what the input is and act accordingly.

If you don’t have control over that, you can poll for changes - so you have a function that fires every n seconds and checks what the text is; if it matches your pattern, stop polling and do what you want.


#6

Yeah, I finally decided just to put a checking function in the function that updated that element; I figure it’s still more efficient that checking even when nothing’s happening to the element.


#7

Generally it’s the best approach. Keep the number of event handlers as low as possible. And if you have that one handler, you can do stuff like abstract out the logic: say, pull the check function out into a generic validator, and when your check function runs, have it look at your validators; if the input matches any of the validations, run the validation logic. Something like (sorry, a bit scrappy here):

const validators = {
  someText: 'i don't want this',
  someNumbers: '1233',
  badSwear: 'dammit',
}

function textInputHandler(e, textValidators) {
  const input = e.target.value
  const valReg = new RegExp(Object.values(textValidators).join('|'), 'i'))

  if (input.match(valReg)) {
    // show user a message saying something
  } else {
    // put the text into the DOM
  }
}