javascript - Select closest element of type "h", e.g. h1, h2, etc - Stack Overflow

admin2025-04-18  2

Assume I select an element using $(mySelector). I would like to select the closest heading to it, so if the closest heading element to it was an <h2>, it would select that, but if the closest was an <h3>, it would select that instead. How can I do this?

Assume I select an element using $(mySelector). I would like to select the closest heading to it, so if the closest heading element to it was an <h2>, it would select that, but if the closest was an <h3>, it would select that instead. How can I do this?

Share Improve this question asked Sep 21, 2012 at 17:58 BluefireBluefire 14.1k24 gold badges79 silver badges121 bronze badges 3
  • I tried closest(), but of course that doesn't tell me just how close it is, so I can't tell it to choose the closest "h", using a switch/if...else if. – Bluefire Commented Sep 21, 2012 at 18:01
  • What is your selector? A child of h2/h3 or a sibling? – Ram Commented Sep 21, 2012 at 18:02
  • A child, i.e. it is within the heading. – Bluefire Commented Sep 21, 2012 at 18:04
Add a ment  | 

1 Answer 1

Reset to default 8

The ma in selectors means "or". So you may do this :

$(mySelector).closest('h3, h2')

This will return 0 or 1 element, the closest if more than one match.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744972638a277578.html

最新回复(0)