0

I want to ask that how I should code a Javascript function that on click to btn_1 main function should execute and during the execution of the main function, the sub-function append to the div which I have created in the main function.

   document.getElementById('btn_1').addEventListener('click', main);


   function subfunc(){

        const h1 = document.createElement('h1');
        h1.appendChild(document.createTextNode('it is working'));
        h1.id = 'heading';
        
    }
    function main(){
        const div = document.createElement('div');
        div.className = 'main-showcase'        
       
    }
1
  • call subfunc(div) in the main method Commented Jun 30, 2020 at 11:53

1 Answer 1

1

You have a few options:

  1. Have the subfunc return the h1 element; have main call it to get the element and append it to the div:

    function subfunc() {
        const h1 = document.createElement('h1');
        h1.appendChild(document.createTextNode('it is working'));
        h1.id = 'heading';
        return h1;
    }
    function main() {
        const div = document.createElement('div');
        div.className = 'main-showcase'        
        div.appendChild(subfunc());
    }
    
  2. Have main pass the div to subfunc and have subfunc do the appending:

    function subfunc(div) {
        const h1 = document.createElement('h1');
        h1.appendChild(document.createTextNode('it is working'));
        h1.id = 'heading';
        div.appendChild(h1);
    }
    function main() {
        const div = document.createElement('div');
        div.className = 'main-showcase'        
        subfunc(div);
    }
    

Or really there are probably several other approaches you could take, but those are the primary two that come to mind.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.