Skip to content

Commit

Permalink
Added missing label error and support for more labelling techniques
Browse files Browse the repository at this point in the history
Adding a clear missing label error message to make it easy to understand what is going wrong if you have not provided a label.

I've also added support for more valid input labelling options.

This fixes this issue:
#2
  • Loading branch information
Dan503 committed May 16, 2019
1 parent b76778b commit c7c4464
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 4 deletions.
48 changes: 45 additions & 3 deletions core/getters/get_label.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,54 @@
var get_ancestors = require('./get_ancestors');

module.exports = function get_label ($input) {
var $forLabel = document.querySelector('label[for="'+$input.id+'"]');
if ($forLabel) return $forLabel;

var labelText =
aria_labelledby($input) ||
aria_label($input) ||
for_attribute($input) ||
label_wrapper_element($input) ||
title_attribute($input);

if (labelText) return labelText;

console.error('Label text for input not found.', $input);
throw new Error('Cannot polyfill time input due to a missing label.');
}

function aria_labelledby($input){
var ariaLabelByID = $input.getAttribute('aria-labelledby');
if (ariaLabelByID) {
var $ariaLabelBy = document.getElementById(ariaLabelByID);
if ($ariaLabelBy) return $ariaLabelBy.textContent;
}
return false;
}

function aria_label($input){
var ariaLabel = $input.getAttribute('aria-label');
if (ariaLabel) return ariaLabel;
return false;
}

function for_attribute($input){
if ($input.id) {
var $forLabel = document.querySelector('label[for="'+$input.id+'"]');
if ($forLabel) return $forLabel.textContent;
}
return false;
}

function label_wrapper_element($input){
var ancestors = get_ancestors($input);
var $parentLabel = ancestors.filter(function($elem){
return $elem.nodeName === 'LABEL';
})[0];
return $parentLabel;
if ($parentLabel) return $parentLabel.textContent;
return false
}

function title_attribute($input){
var titleLabel = $input.getAttribute('title');
if (titleLabel) return titleLabel;
return false
}
2 changes: 1 addition & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ function TimePolyfill($input) {
accessibility_block_created = true;
}

var label = get_label($input).textContent;
var label = get_label($input);

$input.polyfill = {
$a11y: $a11y,
Expand Down

0 comments on commit c7c4464

Please sign in to comment.