How can I create an expression that evaluates whether or not a parent div's descendants are active?

时间:2016-07-11 20:53:20

标签: javascript jquery html if-statement expression

Imagine I have a div with a few descendants/children as such:

<div id="parent" tabindex="0">
  <h1 tabindex="0"> my Header </h1>
  <p tabindex="0"> some text </p>
  <ul tabindex="0">
     <li tabindex="0"> item 1 </li>
     <li tabindex="0"> item 2 </li>
     <li tabindex="0"> item 3 </li>
  </ul>
</div>

How can I create an expression that checks whether or not a child of the 'parent' div is active/has focus? I'd like to perform some action (ex: console log) if the statement evaluates to true.

I'd imagine it's go something like:

if( document.activeelement === <descendant of 'parent' div>) {
     console.log("descendant is active"); 
  }

EDIT: For clarity: The evaluation should occur as an 'if' statement. The expression should translate like so:

if my active element has a parent with an id of 'parent' then do something.

2 个答案:

答案 0 :(得分:0)

do you know the id of the parent and the classnames of the children? or will these be dynamic based on what is clicked? if you know the selector of the parent and children, the following will grab an li element that is a deep or immediate child of the #parent element that is active. if it is empty, then none of those tabs are focused

$(#parent li:focus)

using this jquery selector, we're asking for any li child of the #parent element that is active (:focus).

答案 1 :(得分:0)

You can use click, keydown, keyuyp events attached to document, $("#parent [tabindex]") selector, .is() , :focus

function checkFocus() {
  console.log("descendant is active:"
              , $("#parent [tabindex]").is(":focus")
              , this.activeElement.tagName)
}

$(document).on("click keydown keyup", checkFocus)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent" tabindex="0">
  <h1 tabindex="0"> my Header </h1>
  <p tabindex="0">some text</p>
  <ul tabindex="0">
    <li tabindex="0">item 1</li>
    <li tabindex="0">item 2</li>
    <li tabindex="0">item 3</li>
  </ul>
</div>