Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get child element by ID in JavaScript?

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

like image 852
Burjua Avatar asked Apr 25 '11 22:04

Burjua


People also ask

How will you retrieve an element with the ID first?

The easiest way to access a single element in the DOM is by its unique ID. You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable. Logging demoId to the console will return our entire HTML element.

What is get element by ID in JavaScript?

The getElementById() method returns an element with a specified value. The getElementById() method returns null if the element does not exist. The getElementById() method is one of the most common methods in the HTML DOM. It is used almost every time you want to read or edit an HTML element.


1 Answers

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; 
like image 75
Khez Avatar answered Oct 12 '22 11:10

Khez