How to get child element by ID in JavaScript?

Burjua picture Burjua · Apr 26, 2011 · Viewed 117.4k times · Source

I have following html:

<div id="note">
<textarea id="textid" class="textclass">Text</textarea>
</div>

How can I get textarea element? I can't use document.getElementById("textid") for it

I'm doing it like this now:

var note = document.getElementById("note");
var notetext = note.querySelector('#textid');

but it doesn't work in IE(8)

How else I can do it? jQuery is ok

Thanks

Answer

Khez picture Khez · Apr 26, 2011

If jQuery is okay, you can use find(). It's basically equivalent to the way you are doing it right now.

$('#note').find('#textid');

You can also use jQuery selectors to basically achieve the same thing:

$('#note #textid');

Using these methods to get something that already has an ID is kind of strange, but I'm supplying these assuming it's not really how you plan on using it.

On a side note, you should know ID's should be unique in your webpage. If you plan on having multiple elements with the same "ID" consider using a specific class name.

Update 2020.03.10

It's a breeze to use native JS for this:

document.querySelector('#note #textid');

If you want to first find #note then #textid you have to check the first querySelector result. If it fails to match, chaining is no longer possible :(

var parent = document.querySelector('#note');
var child = parent ? parent.querySelector('#textid') : null;