6

There doesn't seem to be a way in jQuery to tell if a node is a header, i.e., h1, h2, h3, h4, h5, or h6. I'd like to write something like:

hNode$ = $(node).closest('h');
if(hNode$.length >0){
      hNode$.css('padding-top', '+=' + 1);
}

where I bump the top padding if the selected line is a header.

Am I missing something?

Thanks

1 Answer 1

16

Yes there is.

You can select all headers using jQuery(":header")

Here is a link to the documentation: http://api.jquery.com/header-selector/

Note that because this selector is a jQuery extension and not part of the CSS specification, queries using this selector cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using these selectors, first select some elements using a pure CSS selector, then use .filter().

3
  • Should be noted, like it says in the link, that it's not a css standard selector and thus is probably going to be slower than the collective search for all the headers (or, at the very least, not faster).
    – A. Rama
    Commented Feb 6, 2015 at 16:11
  • Yes thank you. l have updated and included that in my answer. Commented Feb 6, 2015 at 16:11
  • 3
    jQuery uses this regex /^h\d$/i to filter elements.
    – skobaljic
    Commented Feb 6, 2015 at 16:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.