Im trying to get the Boolean true
if elements with a certain class name are focused on. But it seems Document.activeElement only works with either ID or Tag name, which wont help since they’re elements of the same type. Heres the situation:
var test2 = document.getElementsByClassName('test2')
var test3 = document.getElementsByClassName('test3')
test3[1].focus()
isFocused2 = (document.activeElement === test2)
isFocused3 = (document.activeElement === test3)
document.getElementById('test').innerHTML = isFocused3
<input type="text" class="test2">
<input type="text" class="test3">
<input type="text" class="test2">
<input type="text" class="test3">
<div id="test"></div>
@Michael It works ONLY if the focus ()
is set to the input as you’ll see below, but clicking on the input doesn’t seem to make it active hence making the isFocused variable stay on false (my mistake in giving you the idea that i wanted to use that method to focus instead of clicking)
const prev = document.getElementsByClassName('prev');
const curr = document.getElementsByClassName('curr');
// curr[1].focus()
var isFocused1 = document.activeElement.classList.contains("prev");
var isFocused2 = document.activeElement.classList.contains("curr");
function fx2 () {
document.getElementById('test').innerHTML += isFocused1 + ' ' + isFocused2 + ' '
}
<table>
<tr>
<td><input type="text" name="" class="prev" onclick="fx2()"></td>
<td><input type="text" name="" class="curr" onclick="fx2()"></td>
<td><p class="Mtr-result"></p></td>
</tr>
<tr>
<td><input type="text" name="" class="prev" onclick="fx2()"></td>
<td><input type="text" name="" class="curr" onclick="fx2()"></td>
<td><p class="Mtr-result"></p></td>
</tr>
<div id="test"></div>
as you can see the focus method has been commented out, and the onclick event attribute on the input calls the fx2()
function that changes the innerHTML value of the ‘test’ div to the value of isFocused 1 and 2, which both show false.
2
Answers
As Bergi and Zachiah pointed out in the comments, all you need to do is use
document.activeElement.classList.contains("test2")
to check if the focused element has thetest2
class.Element.classList.contains(class)
is a method that you can call on any element, includingdocument.activeElement
. If the element you’re calling it contains the class passed to the method, then it will returntrue
, otherwise it will returnfalse
.document.activeElement
works fine 🙂: