简体   繁体   中英

How can I insert element using DOM JavaScript

This code only works on some consoles...

I would like a div to appear before the button when clicked, using only DOM.

How can I fix this code????

<html>
    <body>
        <div id ='div'>
        <button id = 'button'>click me!</button>
        </div>

        <script>
            var button = document.getElementById('button');
            var div = document.getElementById('div');
            var appearingDiv = document.createElement('div');
            var appearingDivText = document.createTextNode("Hi how are you? Hi how are you?Hi how are you?Hi how are you?Hi how are you?Hi how are you?Hi how are you?Hi how are you?Hi how are you?Hi how are you?Hi how are you?Hi how are you?Hi how are you?Hi how are you?Hi how are you?Hi how are you?Hi how are you?Hi how are you?Hi how are you?Hi how are you?Hi how are you?Hi how are you?Hi how are you?Hi how are you?Hi how are you?Hi how are you?Hi how are you?Hi how are you?Hi how are you?");
            
            appearingDiv.appendChild(appearingDivText);
            
            button.addEventListener('click',buttonClicked);
            
            function buttonClicked(){
                div.insertBefore(appearingDiv,button);
            }   
                
        </script>
        
    </body>
</html>```


insertBefore method takes two parameters 'reference' but you are only passing one parameter.

Solution:

 <!DOCTYPE html> <html> <body> <div class="header"> <div class="old">This is paragraph 1</div> </div> <script> //New Element var newDiv = document.createElement('div'); var newDivText = document.createTextNode('this is a new div!'); newDiv.appendChild(newDivText); //Add to header div var container = document.querySelector('div.header'); var oldDiv = document.querySelector('div.old'); container.insertBefore(newDiv, oldDiv); </script> </body> </html>

It's a typo: insertBefore('newDiv, oldDiv'); You are passing in a string, remove the single quotes around newDiv, oldDiv -> insertBefore(newDiv, oldDiv); – Ryan Wilson

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