简体   繁体   中英

Javascript/HTML Oninput with div

I've made oninput for div with a class. I can't add an ID to the div . So here is my script:

var objecto = document.getElementsByClassName(" nicEdit-main ")[0];
objecto.oninput = function() {
    alert("Ok!");
}  

Here is my HTML:

<div class=" nicEdit-main   " style="width: 499px; margin: 4px; min-height: 149px; overflow: hidden;" contenteditable="true">1123215545<br></div>

Why does oninput not work for this div?

It should just work fine, make sure your script is executed after the target element is loaded in the dom.

1 way is to use the dom ready/window load event handler

 window.addEventListener('load', function() { var objecto = document.getElementsByClassName(" nicEdit-main ")[0]; objecto.oninput = function() { alert("Ok!"); } }) 
 <div class=" nicEdit-main " style="width: 499px; margin: 4px; min-height: 149px; overflow: hidden;" contenteditable="true">1123215545 <br> </div> 


Another is to place the script after the element like

 <div class=" nicEdit-main " style="width: 499px; margin: 4px; min-height: 149px; overflow: hidden;" contenteditable="true">1123215545 <br> </div> <script> var objecto = document.getElementsByClassName(" nicEdit-main ")[0]; objecto.oninput = function() { alert("Ok!"); } </script> 

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