如何使用纯js访问新创建的元素

How to access newly created elements by pure js?

本文关键字:创建 元素 新创建 何使用 js 访问      更新时间:2023-09-26

我制作了一些"warning"层来代替"alert()"。

code :
warning = document.getElementById('warning'); // This line is what exactly I want to make functional. the code out side of warning(); This line runs before 'elem:div#warning' is made by warning().
function warning() {
a = document.createElement('div');
document.body.appendChild(a);
a.id = 'warning';
a.className= 'warning';
}

但我不知道如何通过javascript访问新创建和添加的元素。

我认为css可以很好地处理新添加的元素。但js不是。

我在谷歌上搜索了一下,发现一些方法使用原型自动注册新创建的元素,但我很难理解…

所以,我想做的是,通过在创建"a"之前执行的javascript访问新创建的元素"a"。

我试过这个方法:

if(document.getElementById('warning')) {alert('asdf')};

但它没用。。。

试试这个小提琴,它对我有用,做了一些小改动。

function warning() {
   a = document.createElement('div');
   document.body.appendChild(a);
   a.id = 'warning';
   a.className= 'warning';
}
warning();
warningDiv = document.getElementById('warning');
if(document.getElementById('warning')) {
  alert('warning div on DOM')
};