Selecting multiple elements with the same id using querySelectorAll and use the returned nodelist object

Costas

Administrator
Staff member
bQqekvd.png

The querySelectorAll, return the select items as Nodelist object. NodeList is not an Array, it is possible to iterate on it using forEach(). It can also be converted to an Array using Array.from(). (more)

Trigger the event
WjhPmli.png

the e, is the mouse event, to get the actual 'source' element that clicked we use e.srcElement

tXdUcqW.png


to get the parent, we using the e.srcElement.parentNode

dPvzQHv.png




Put it all together

JavaScript:
//example of TR

[TR]
	
[TD]  //first TD
		[img]assets/cat_icon.png[/img]
	[/TD]


[TD]  //second TD
		[url='list_topics.php?id=1']Health[/url]
	[/TD]


[TD]2018-06-04[/TD]


[TD]
		[B][/B]
	[/TD]


[TD]  //fourth TD
		<a id="btn_edit" class="btn btn-primary btn-xs">Edit</a>
	[/TD]

[/TR]

yUMcTUY.png


 

 

JavaScript:
var tbl_btns = document.querySelectorAll("#btn_edit");

tbl_btns.forEach(function(elem) {
	elem.addEventListener("click", function(e) {
		e.preventDefault();
		var x = getSelected(e.srcElement);
		console.log(x);
	});
});

function getSelected(e){

	//first TD
	var id = e.parentNode.parentNode.cells[0].children[0].getAttribute('data-id');
	
	//second TD
	var forum_name = e.parentNode.parentNode.cells[1].children[0].text;
	
	//fourth TD
	var forum_private = e.parentNode.parentNode.cells[3].childElementCount;
	
	return { id, forum_name, forum_private };
}




Optimize more!

JavaScript:
Array.prototype.forEach.call(document.querySelectorAll('#btn_edit'), function(el) {

	el.addEventListener('click', function(e) {
		e.preventDefault();
		var x = getSelected(e.srcElement);
		console.log(x);
	})
	
})

function getSelected(e){

	var tr = e.parentNode.parentNode;

	var id = tr.cells[0].children[0].getAttribute('data-id');
	var forum_name = tr.cells[1].children[0].text;
	var forum_private = tr.cells[3].childElementCount;
	
	return { id, forum_name, forum_private };
}

 

greets to https://plainjs.com/ and joyrexus
 
Top