最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

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

matteradmin6PV0评论

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.

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far