Adam Adam - 20 days ago 7
Javascript Question

Check if active element has particular class via javascript

I'm writing a single-field form and want the Enter key to advance the form to the next input field. Since there's another form on the page, I only want the Enter key to advance the form when one of the inputs in that form is the

activeElement
.

I've achieved this with what seems like an extremely verbose
if()
statement here:

document.addEventListener( 'keydown', function( ev ) {
var keyCode = ev.keyCode || ev.which;
var ids = [ 'this', 'that', 'there', 'thing', 'other' ];
if ( document.getElementById( ids[0] ) === document.activeElement || document.getElementById( ids[1] ) === document.activeElement || document.getElementById( ids[2] ) === document.activeElement || document.getElementById( ids[3] ) === document.activeElement || document.getElementById( ids[4] ) === document.activeElement) {
if( keyCode === 13 ) {
ev.preventDefault();
self._nextQuestion();
}
}
} );


Each of the inputs are the same class:
.questions
. I've tried something like:

document.addEventListener( 'keydown', function( ev ) {
var keyCode = ev.keyCode || ev.which;
var ids = [ 'this', 'that', 'there', 'thing', 'other' ];
if ( document.querySelector('.questions') === document.activeElement) {
if( keyCode === 13 ) {
ev.preventDefault();
self._nextQuestion();
}
}
} );


But of course, this only accesses the first instance of
.questions
on the page. I don't want to iterate over nodes, as it doesn't seem much better than what I have already.

I'm a novice, and I'm looking for more concise logic.

Answer

Just check if the activeElement has the questions class.

var pattern = /(?:^|\s)questions(?:\s|$)/
if (document.activeElement.className.match(pattern)) {
  ...
}

squint provided an improved regex that will account for more funky situations in the classname.