src/Page.js
function getClosestHeading($, headingsSelector, element) {
  const prevElements = $(element).prevAll();
  for (let i = 0; i < prevElements.length; i += 1) {
    const currentElement = $(prevElements[i]);
    if (currentElement.is(headingsSelector)) {
      return currentElement;
    }
    const childHeadings = currentElement.find(headingsSelector);
    if (childHeadings.length > 0) {
      return childHeadings.last();
    }
  }
  if ($(element).parent().length === 0) {
    return null;
  }
  return getClosestHeading($, headingsSelector, $(element).parent());
}
function getClosestHeading($, headingsSelector, element) {
  const prevElements = $(element).prevAll();
  for (let i = 0; i < prevElements.length; i += 1) {
    const currentElement = $(prevElements[i]);
    if (currentElement.is(headingsSelector)) {
      return currentElement;
    }
    const childHeadings = currentElement.find(headingsSelector);
    if (childHeadings.length > 0) {
      return childHeadings.last();
    }
  }
  if ($(element).parent().length === 0) {
    return null;
  }
  return getClosestHeading($, headingsSelector, $(element).parent());
}
function getClosestHeading ( $ , headingsSelector , element ) { const prevElements = $ ( element ) . prevAll ( ) ; for ( let i = 0 ; i < prevElements . length ; i += 1 ) { const currentElement = $ ( prevElements [ i ] ) ; if ( currentElement . is ( headingsSelector ) ) { return currentElement ; } const childHeadings = currentElement . find ( headingsSelector ) ; if ( childHeadings . length > 0 ) { return childHeadings . last ( ) ; } } if ( $ ( element ) . parent ( ) . length === 0 ) { return null ; } return getClosestHeading ( $ , headingsSelector , $ ( element ) . parent ( ) ) ; }
Gets the closest heading to an element
@param $ a Cheerio object
@param headingsSelector jQuery selector for selecting headings
@param element to find closest heading
Gets the closest heading to an element