Shift N' Tab Shift N' Tab - 2 months ago 14
HTML Question

How to get a child element by id by its parent id element using pure Javascript

In the given code below, the

div#item-1
of the
div#parent-1
was only hidden.

But how can i do that by specifying the parent?

AND

How can i do that by hiding both the
#item-1
element?




function HideElement(id)
{
var doc = document.getElementsByClassName(id);
doc.style.visibility = 'hidden';
}

HideElement('item-1');

#parent-1
{
background: red;
}

#parent-2
{
background: blue;
}

<div id="parent-1">
<div class="item-1">Item 1</div>
<div class="item-2">Item 2</div>
<div class="item-3">Item 3</div>
</div>

<div id="parent-2">
<div class="item-1">Item 1</div>
<div class="item-2">Item 2</div>
<div class="item-3">Item 3</div>
</div>





UPDATE



I replace the child element
id
attribute to
class
but the problem is how can i access the style property of the element?

I've got this error:

Uncaught TypeError: Cannot set property 'visibility' of undefined

Answer

edit: I've taken some of the recommendations in the comments and put them into this answer.

You're better off using class or data- attributes instead of ids. As pointed out ids should be unique, so there can be only one of each on a page. Consider the following html & js:

<div id="parent-1">
  <div class="item-1"></div>
  <div class="item-2"></div>
  <div class="item-3"></div>
</div>

<div id="parent-2">
  <div class="item-1"></div>
  <div class="item-2"></div>
  <div class="item-3"></div>
</div>

css:

.item-hidden{
  visibility: hidden;
}

javascript:

function hideElement(selector){

  var items = document.querySelectorAll(selector);

  for(var i = 0, l = items.length; i < l; ++i){
    items[i].classList.add('item-hidden');
  }

}

//usage:
hideElement('.item-1'); // will hide all '.item-1' elements
hideElement('#parent-1 div'); // will hide all <div>s inside of #parent-1

querySelectorAll() reference

classList reference

edit: About the update on the question:

document.getElementsByClassName(); will return a nodelist, instead of just one node. Notice the 's' in getElementsByClassName. You'll have to use a loop like in this answer to change properties for each node.