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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//example of TR

<tr class="topics">

<td>  //first TD
		![](assets/cat_icon.png)
	</td>

<td>  //second TD
		[Health](list_topics.php?id=1)
	</td>

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

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

<td>  //fourth TD
		[Edit]()
	</td>

</tr>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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

origin - http://www.pipiscrew.com/?p=13786 selecting-multiple-elements-with-the-same-id-using-queryselectorall-and-use-the-returned-nodelist-object

This post is licensed under CC BY 4.0 by the author.
Contents

Trending Tags