0

I want understand how can i get a element with id of 'takeme' in other context that is not the document, for example:

<div id="parent">
  <div id="takeme"></div>
</div>

I know that i can use:

document.getElementById('takeme');

being document the context, now i want know how can i get the takeme from the parent, without using queryselectorall, so i was trying to:

var parent = document.getElementById('parent');
parent.getElementById('takeme');

but of course didn't work.

Patrick Evans
  • 41,991
  • 6
  • 74
  • 87

2 Answers2

2

getElementById for an HTMLElement will not work because getElementById is only defined for document. There is a Document.getElementById but there is not an Element.getElementById.

As commenters have mentioned, it is not needed from a parent node since the id should be unique to the document.

However, other methods like Element.getElementsByClassName should work for a different context(HTMLElement)

var parent = document.getElementById('parent');
var fromOtherContext = parent.getElementsByClassName('takeme');
console.log(fromOtherContext);

fromOtherContext = parent.getElementById('takeme');
console.log(fromOtherContext);//only works for document
<div id="parent">
  <div class="takeme"></div>
  <div class="takeme"></div>
  <div class="takeme"></div>
  <div id="takeme"></div>
</div>
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
1

if you can put a class in addition to the ID

<div id="takeme" class="takeme"></div>

Then

var parent = document.getElementById('parent');
var takeme = parent.getElementsByClassName('takeme');