如何通过纯js​​访问新创建的元素?

时间:2014-09-22 07:00:06

标签: javascript

我做了一些警告'要使用的图层而不是' 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')};

但它没用了......

1 个答案:

答案 0 :(得分:0)

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

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')
};