Inserting elements using Javascript

Discussion in 'JavaScript' started by naif, Nov 6, 2007.

  1. #1
    Hi everyone. I have the following code:

    
    <div id="page">
    	content content
    </div>
    
    Code (markup):
    Using Javascript, I want to add a <div class="right"> right next to <div id="page"> so that the browser would render the code as:

    
    <div id="page"><div class="right">
    	content content
    </div></div>
    
    Code (markup):
    Is this possible. And how difficult would it be?

    Looking forward for a solution.

    Thanks,
    -- Naif
     
    naif, Nov 6, 2007 IP
  2. rohan_shenoy

    rohan_shenoy Active Member

    Messages:
    441
    Likes Received:
    20
    Best Answers:
    0
    Trophy Points:
    60
    #2
    Not 100& sure but I think the following will automatically add the required codes as the page loads:

    
    <div id="page"><script src="/code1.js"></script>
    	content content
    <script src="/code2.js"></script></div>
    
    Code (markup):
    Create a new javascript file by the name code1.js. Paste the below code into that file:
    
    document.write('div class="right"')
    
    Code (markup):
    Now create a new javascript file by the name code2.js. Paste the below code into that file:
    
    document.write('</div>')
    
    Code (markup):
    Upload the code1.js and code2.js files to server and check if it has effected
     
    rohan_shenoy, Nov 7, 2007 IP
  3. naif

    naif Well-Known Member

    Messages:
    468
    Likes Received:
    19
    Best Answers:
    0
    Trophy Points:
    118
    #3
    Hmm. I guess it would but I cant use that. The reason I want to use javascript for this is so that I can completely move presentational elements from the HTML code and keep only thoe elements which have a structural meaning. Doing that would just beat what I am trying to achieve here. Thanks though. I am still looking for a solution

    -- Naif
     
    naif, Nov 7, 2007 IP
  4. phper

    phper Active Member

    Messages:
    247
    Likes Received:
    17
    Best Answers:
    0
    Trophy Points:
    60
    #4
    naif, I'm with you there. I don't like the use of .innerHTML either.

    Try using DOM instead:
    var origDiv = document.getElementById("page");
    var newDiv = document.createElement("DIV");
    newDiv.className = "right";
    newDiv.appendChild(document.createTextNode(origDiv.firstChild.data));
    origDiv.replaceChild(newDiv, origDiv.firstChild);
    Code (markup):
    This is assuming the 'page' div initially has only text in it. If it has other elements, you'll just need to loop through each child node and append it to the newly created div.
     
    phper, Nov 8, 2007 IP