简体   繁体   中英

Pass 'div' element as parameter to JavaScript function

I need to create, decorate and append child 'divs' to existing. For example, after the appendChildren is executed, following divs

    <div id="a">
      <div id="b">
      </div>
    </div>

should take the following form (assuming decorateDiv adds text "This is new div" inside new div)

    <div id="a">
      <div id="b">
        <div>"This is new div"</div>
      </div>
      <div>"This is new div"</div>
    </div>

Here is my code

    function appendChildren() {
    var allDivs = document.getElementsByTagName("div");
    for (var i = 0; i < allDivs.length; i++) {
    var newDiv = document.createElement("div");
    decorateDiv(newDiv);
    allDivs[i].appendChild(newDiv);
    }
    }


    function decorateDiv(div) {
      var x = document.getElementByTagName("div");
      var t = document.createTextNode("This is new div");  
    x.appendChild(t); 
    }

I am completely new to JavaSpript. What am I doing wrong? Please help me to fix bugs

The parameter 'div' that you are passing to function 'decorateDiv' has nowhere been used. You can change your decorateDiv function like as below:

function decorateDiv(div) {  
var t = document.createTextNode("This is new div");   
div.appendChild(t);   
}

Hope this helps!!

You're not using the parameter div and the decorateDiv should look like this:

function decorateDiv(div) {
   //div is the object element
   var t = document.createTextNode("This is new div");  
   div.appendChild(t); 
}

"allDivs" variable get update when to appendChild to any div because to stores array of elements of "div" TagName. So, use class for fetching divs.

<div id="a" class="test">
A  
<div id="b" class="test">
    B  
</div>
</div>

Here is user script:

function appendChildren() {
        var allDivs = document.getElementsByClassName("test");
            for (var i = 0 ; i < allDivs.length ; i++) {
                var newDiv = document.createElement("div");
                decorateDiv(newDiv);
                allDivs[i].appendChild(newDiv);
            }
        }
        function decorateDiv(div) {
          var t = document.createTextNode("This is new div");  
            div.appendChild(t); 
        }
        appendChildren();

And also you are not using parameter passed to decorative function.

This will work. Try this..

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