4

How to replace div with another div in javascript?

This is what I have:

<div id="main_place">
main
</div>

<button onclick="show(operation1)">Replace to operation 1</button>
<button onclick="show(operation2)">Replace to operation 2</button>
<button onclick="show(operation3)">Replace to operation 3</button>


<div id=operation1 style=“display:none”>
Some textboxes and text
</div>

<div id=operation2 style=“display:none”>
Again some textboxes and text
</div>

<div id=operation3 style=“display:none”>
And again some textboxes and text
</div>

<script>
function show(param_div_id){
        document.getElementById('main_place').innerHTML = Here should be div from param;
        }
</script>

Is it even possible to do it without jquery?

4
  • 9
    "Is it even possible to do it without jquery?" jQuery is nothing but JavaScript... Anything that can be done with jQuery can be done without it. Commented May 20, 2016 at 13:15
  • Yes i know it but i'd like to use raw JavaScript Commented May 20, 2016 at 13:17
  • developer.mozilla.org/en-US/docs/Web/API/Node/replaceChild Please actually try to google next time. Commented May 20, 2016 at 13:21
  • jsfiddle.net/shvf1r42 - is this what you want to or do you want to replace the new div with main_place? Commented May 20, 2016 at 13:22

7 Answers 7

16

Pass strings into your method and get the other div

<div id="main_place">
  main
</div>

<button onclick="show('operation1')">Replace to operation 1</button>
<button onclick="show('operation2')">Replace to operation 2</button>
<button onclick="show('operation3')">Replace to operation 3</button>


<div id=operation1 style=“display:none”>
  Some textboxes and text
</div>

<div id=operation2 style=“display:none”>
  Again some textboxes and text
</div>

<div id=operation3 style=“display:none”>
  And again some textboxes and text
</div>

<script>
  function show(param_div_id) {
    document.getElementById('main_place').innerHTML = document.getElementById(param_div_id).innerHTML;
  }
</script>

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

7 Comments

I'd suggest some alternatives to innerHTML and inline event handlers.
@Cerbrus I believe DiPix was simply trying to finish his code. This was it. Next improve
True, but SO answers should strive to fix all problems with an OP's code, where possible.
This is also true, SO is a community... I can't promise to fix all your problems but I can promise you that you won't have to face them all alone ;)
@Lee.Winter is the hero of the day :-)
|
12

2019 Update:

child.replaceWith(newElement);

https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/replaceWith

In the specific case of this question, I would recommend using replaceWith with a clone of the node OP wishes to swap in. This could look like:

const main = document.getElementById('main');
const original = document.getElementByid('operation1');
const clone = original.cloneNode(true);

main.replaceWith(clone);

This would probably present an issue the next time you go to swap the element, but you could adapt this solution to fit your needs.


Original Post:

The best way to do this would be to not use innerHTML, due to possible unforseen side effects. The best way to do this would be to:

  • First clone the desired div
  • Second empty the main div
  • Third append the clone into the main div

This would look very much like the following:

function swapContent (id) {
    const main = document.getElementById('main');
    const div = document.getElementById(id);
    const clone = div.cloneNode(true);

    while (main.firstChild) main.firstChild.remove();

    main.appendChild(clone);
}

Do not allow yourself to fall into the many pitfalls of using innerHTML; cloning a node has a much better chance of doing exactly what you're expecting it to do.

Some of the problems with innerHTML are that it only copies the HTML, and not the DOM, meaning that you do not copy over anything on that DOM node, like event listeners, properties (like value), etc. Cloning a node (and its children) clone that DOM node, which clones its properties respectively.

It is also considered poor practice (by most) to use inline event handlers on your HTML; separation of concerns!

12 Comments

Could you be more specific about these "possible unforeseen side effects", it's very spurious to say that while bashing another perfectly acceptable answer, it would help if you were more constructive
campaign:5 Uncaught TypeError: Cannot read property 'firstChild' of null, why?
using innerHTML not only clears event listeners on the node that you're setting it on, but it also does not carry over any event listeners of the children of that HTML (unless you're using inline HTML events, which is also poor practice). Please, let's just write good code, yeah?
@ndugger - Good link, but knowledge of when and how to use things is more important, it's not globally "bad" just because of that article you linked. I know if I hit my toe with a hammer it will hurt, but that doesn't make the hammer bad. Either way, thanks for the edit, that's much more helpful for future readers.
@DiPix What parts specifically? It's extremely simple code; I suggest you check out CodeCademy.com to learn the basics of the language before you try to write it.
|
1

i used this form for replace my divs.

<div id="newDiv" class="here" style="display: none" > content</div>
<div id="oldDiv" class="here" style="display: block"> content</div>
<button type="button" onclick="newDivHere()">replace</button>

and JS:

function newDivHere() {
document.getElementById("oldDiv").style.display="none";
document.getElementById("newDiv").style.display="block";
}

3 Comments

While this is a good solution to hide one div and show another, it may not be a "correct" solution here, in that OP asked specifically how to "swap", or "replace" an element or its content. I will still +1 your post, though, since you're new.
i need this but with multiple buttons and i cannot figure it out
just like in the question example but instead of change the content, actually replace one div with another when the menu buttons are clicked
0

Edit your javascript like this:

function show(param_div_id){
    document.getElementById('main_place').innerHTML = document.getElementById(param_div_id).textContent;
}


And also, put your parameters inside single-quotes like this:

<button onclick="show('operation1')">

Comments

0

Try like this

document.querySelector('#maincontent').outerHTML = jsonResponse.main;

Comments

-1

just assign the HTML content to a string (manually written or fetched from another html element (template)):

window.onload = function() {
  document.getElementById("to_be_replaced").innerHTML = "<span> My Production Text </span>";
}
div > span {
  font-weigth: bold;
  color: red;
  }
<div id="to_be_replaced">
  Lorem ipsum...
</div>

Comments

-2

i think ndugger is right and you should use something like delete/colon or in jquery .remove() and append() instead of innerhtml.

according to this question in stackoverflow and other sites always better use append() instead of html() or innerHTML.

"innerHTML += ..." vs "appendChild(txtNode)"

your code can be like this.

        function swapContent(id) {
            const main = document.getElementById('main_place');
            const div = document.getElementById(id);
            const clone = div.cloneNode(true);

            while (main.firstChild) main.firstChild.remove();

            main.appendChild(clone);
        }
    <div id="main_place">
        main
    </div>

    <button onclick="swapContent('operation1')">Replace to operation 1</button>
    <button onclick="swapContent('operation2')">Replace to operation 2</button>
    <button onclick="swapContent('operation3')">Replace to operation 3</button>

    <div id="complete" style="display:none;">
        <div id="operation1">
            Some textboxes and text
        </div>

        <div id="operation2">
            Again some textboxes and text
        </div>

        <div id="operation3">
            And again some textboxes and text
        </div>
    </div>

also you can use

document.getElementById("idOfDIv").addEventListener("click", function () {
    yourfunction();
    secondfunction();
})

or this

document.getElementById("idOfDIv").onclick = yourfunction();

instead of inside HTML onclick Event Attribute

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.