Skip to content

Instantly share code, notes, and snippets.

@jakejscott
Created June 24, 2015 03:26
Show Gist options
  • Save jakejscott/728902f8a50025d0a538 to your computer and use it in GitHub Desktop.
Save jakejscott/728902f8a50025d0a538 to your computer and use it in GitHub Desktop.
Vanilla JS Table row toggle
function getClosest(elem, selector) {
var firstChar = selector.charAt(0);
for (; elem && elem !== document; elem = elem.parentNode) {
if (firstChar === '.') {
if (elem.classList.contains(selector.substr(1))) {
return elem;
}
}
if (firstChar === '#') {
if (elem.id === selector.substr(1)) {
return elem;
}
}
if (firstChar === '[') {
if (elem.hasAttribute(selector.substr(1, selector.length - 2))) {
return elem;
}
}
if (elem.tagName.toLowerCase() === selector) {
return elem;
}
}
return false;
};
function ready(fn) {
if (document.readyState != 'loading') {
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
ready(function () {
var elements = document.querySelectorAll('.expand-json');
for (var i = 0; i < elements.length; i++) {
var el = elements[i];
el.addEventListener('click', function (event) {
var tr = getClosest(event.target, 'tr');
var nexttr = tr.nextElementSibling;
if (nexttr.style.display === 'none') {
nexttr.style.display = '';
} else {
nexttr.style.display = 'none';
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment