Alexandr Belov Alexandr Belov - 8 months ago 24
Javascript Question

Find dynamically added elem.firstChild

I've got some code for dynamically added tabs with content. When removing a tab, eventListener launches a callback function which takes an array of tab + content as parameters.

[newTab] - array of dynamically created tabs

[newContent] - array of dynamically created divs (tabs content)
Here's the code for that:

tabSpan.addEventListener("click", removeTab([newTab, newContent]));

The thing is when I remove a tab with class active I need to pass this class to the first tab in array if it exists, if not - do nothing.
The issue I am trying to solve is that my removeTab function doesn't get the first child of newTab array.

//Remove tab
function removeTab(nodeArr) {
return function() {

nodeArr.forEach(function(el) {

el.parentNode && el.parentNode.removeChild(el);



console.log displays null

How can I retrieve that firstChild in my case to pass class active to it?

HTML (do not pay attention to the defaultTab, it doesn't count as firstChild in this case):

<div class="wrap">

<ul id="tabs">

<li id="defaultTab" class="tab default">

</ul><!--Tabs ul End-->

<div id="defaultDiv" class="content default">




It display null because closest is looking for it's parent, not children.

What is closest() method?

According to MDN

The Element.closest() method returns the closest ancestor of the current element (or the current element itself) which matches the selectors given in parameter.

What is ancestor?

According to W3school

An ancestor is a parent, grandparent, great-grandparent, and so on.

So we should look for child element. We can use querySelector() here.

What is querySelector?

According to MDN

Returns the first element within the document

Also we have to avoid javascript is loading before DOM and can use setTimeout here. So final code is

setTimeout(function waitDom() {
   }, 0);

Here is the working fiddler.