简体   繁体   English

JS-创建的元素上的getElementById

[英]JS - getElementById on created element

I am trying to find an element with getElementById inside another element. 我正在尝试在另一个元素内找到带有getElementById的元素。 Both elements were created with JS and have not yet been appended to the body. 这两个元素都是使用JS创建的,尚未添加到主体。 Sadly, I get the following error: myElement.getElementById is not a function . 可悲的是,我收到以下错误: myElement.getElementById不是一个函数

Here is an example of what I am trying to do. 这是我正在尝试做的一个例子。 Is there a way for this to work? 有办法吗?

parentElement = document.createElement("div");
childElement = document.createElement("div");
childElement.id = "child";
parentElement .appendChild(childElement);

myElement = parentElement.getElementById("child");

For a more detailed example, this is what I am trying to do exactly: I am making a date picker from scratch (for funz) and I have an element which displays the month and year. 对于更详细的示例,这就是我要尝试做的事情:我正在从头开始创建一个日期选择器(用于funz),并且有一个显示月份和年份的元素。 You can change the month and year and I therefore need to change the innerHTML of this element when that happens. 您可以更改月份和年份,因此,当发生这种情况时,我需要更改此元素的innerHTML。 Instead of recreating the whole calendar, I thought it would be cleaner to just change the days and the month/year label. 与重新创建整个日历相比,我认为只更改日期和月/年标签会更干净。 To do this, using getElementById().innerHTML seemed natural. 为此,使用getElementById()。innerHTML似乎很自然。

There is no getElementById method on DOM element. DOM元素上没有getElementById方法。 id has to be unique. id必须是唯一的。 So you can easily find it using document.getElementById . 因此,您可以使用document.getElementById轻松找到它。

Why do you try to get element by id when you already have it in childElement variable? 当在childElement变量中已有元素时,为什么要尝试通过id获取元素?

Turns out you can't getElementById() for elements that are not in the document. 事实证明,对于不在文档中的元素,您无法获取ElementById()。

The solution is to add an if/else condition to check if the element is in the body or not to get the results you want in both cases. 解决方案是添加一个if / else条件,以检查元素是否在主体中,以在两种情况下均获得所需的结果。

Saddly adds a few lines of code. 遗憾地添加了几行代码。 It's no biggie but it would seem natural to use getElementById() since other functions like getElementsByClassName() work in cases like these. 没什么大不了的,但是使用getElementById()似乎很自然,因为诸如getElementsByClassName()之类的其他函数可以在这种情况下工作。 Maybe one day... 也许有一天...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM