JavaScript中如何通过ID获取子元素?
我有以下 html:
<div id="note">
<textarea id="textid" class="textclass">Text</textarea>
</div>
如何获取 textarea 元素?我不能使用 document.getElementById("textid")
我现在这样做:
var note = document.getElementById("note");
var notetext = note.querySelector('#textid');
但它在 IE(8) 中不起作用
我还能怎么做? jQuery 没问题,
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果 jQuery 没问题,您可以使用 find()。这基本上相当于你现在的做法。
您还可以使用 jQuery 选择器来基本上实现相同的目标:
使用这些方法来获取已经有 ID 的东西有点奇怪,但我提供这些方法是假设这并不是您真正计划使用它的方式。
另外,您应该知道 ID 在您的网页中应该是唯一的。如果您计划让多个元素具有相同的“ID”,请考虑使用特定的类名称。
更新 2020.03.10
使用原生 JS 可以轻松实现此目的:
如果您想先查找
#note
,然后查找#textid
,则必须检查第一个 querySelector 结果。如果无法匹配,则不再可能进行链接:(If jQuery is okay, you can use find(). It's basically equivalent to the way you are doing it right now.
You can also use jQuery selectors to basically achieve the same thing:
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:
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 :(这是一个纯 JavaScript 解决方案(没有 jQuery)
的使用示例:
Here is a pure JavaScript solution (without jQuery)
Example of use:
使用 jQuery
或者只是
Using jQuery
or just
函数查找所选 DOM 内的所有 dom 对象。
即
如果你写在这里;
你将得到树 p 元素。另一方面,
函数在所选 DOM 对象的子 DOM 中进行搜索。因此,通过这段代码,您将只得到第 1 段和第 2 段。防止浏览器执行不必要的操作非常有益。
function looking for all dom objects inside the selected DOM.
i.e.
here if you write;
you will get tree p elements together. On the other side,
Function searching in the just children DOMs of the selected DOM object. So, by this code you will get just paragraph 1 and paragraph 2. It is so beneficial to prevent browser doing unnecessary progress.