Ascribe function to newly created element

I’d like to make a new created table sortable.
The following code only works if the table is already existing.
After having searched the net, it seems that I should bind On to newly created elements.
However, I am not sure how to do this in this example.

	var table = document.querySelector('#tbl'),
		ths = table.querySelectorAll('thead th'),
		trs = table.querySelectorAll('tbody tr');

	function makeArray(nodeList){
		var arr = [];

		for(var i=0; i < nodeList.length; i++){
		return arr;

	function clearClassName(nodeList){
		for(var i=0; i < nodeList.length; i++){
			nodeList[i].className = '';
	function sortBy(e){
		var target =;
		var thsArr = makeArray(ths);
		var trsArr = makeArray(trs);
		var index = thsArr.indexOf(target);
		var df = document.createDocumentFragment();
		var order = (target.className === '' || target.className === 'desc') ? 'asc' : 'desc';


			var tdA = a.children[index].textContent;
			var tdB = b.children[index].textContent;
			if(tdA < tdB){
				return (order === 'asc'? -1 : 1)
			}else if (tdA > tdB){
				return (order === 'asc'? 1 : -1)
				return 0;


		target.className = order;

	for(var i = 0; i < ths.length; i++){

		ths[i].addEventListener('click', sortBy);

You attach the listener to the table and when the event listener is executed, you check if the desired element is an ancestor element of the event target (this is called a delegated event).

Hello Dormilich,

The table is already attached to the table:

var table = document.querySelector('#tbl'),
ths = table.querySelectorAll('thead th'),
ths[i].addEventListener('click', sortBy);

But the table does not exist upon loading the page, and thus resulting in an error:

TypeError: table is null

Please excuse my ignorance, this is quite new to me.

if the table doesn’t exist then you need to use an element that exists and will be an ancestor of the table.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.