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


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

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

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


Put it all together

//example of TR

<tr class="topics">
	
<td>  //first TD
		<img src="assets/cat_icon.png" class="img-polaroid" data-id="1">
	</td>


<td>  //second TD
		<a href="list_topics.php?id=1">Health</a>
	</td>


<td>2018-06-04</td>


<td>
		<span class="glyphicon glyphicon-ok"></span>
	</td>


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

</tr>

 

 

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!

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

By: |05/06/2018|categories: