Created
June 24, 2015 03:26
-
-
Save jakejscott/728902f8a50025d0a538 to your computer and use it in GitHub Desktop.
Vanilla JS Table row toggle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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