简体   繁体   中英

How to access newly created elements by pure js?

I made some 'warning' layer to use instead of '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';
}

But I don't know how to access that newly created and added element by javascript.

I think css works fine with newly added elements. But js is not.

I searched google, and found some methods register newly created element automatically using prototype, but it was hard to understand to me...

So, what I trying to do is, access to newly created element 'a' by javascript which executed before that 'a' was created.

I tried this method :

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

But it was useless...

Try this fiddle , it works for me, did small change.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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