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?

DiPix
  • 5,755
  • 15
  • 61
  • 108
  • 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. – blex May 20 '16 at 13:15
  • Yes i know it but i'd like to use raw JavaScript – DiPix May 20 '16 at 13:17
  • https://developer.mozilla.org/en-US/docs/Web/API/Node/replaceChild Please actually try to google next time. – ndugger May 20 '16 at 13:21
  • https://jsfiddle.net/shvf1r42/ - is this what you want to or do you want to replace the new div with `main_place`? – messerbill May 20 '16 at 13:22

7 Answers7

17

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>
Lee.Winter
  • 700
  • 9
  • 16
13

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!

ndugger
  • 7,373
  • 5
  • 31
  • 42
  • 1
    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 – Daniel Dawes May 20 '16 at 13:37
  • `campaign:5 Uncaught TypeError: Cannot read property 'firstChild' of null`, why? – DiPix May 20 '16 at 13:38
  • 1
    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 May 20 '16 at 13:39
  • @DiPix because you do not have a div with the id of "main"--I am not in the business of writing code for you, this is just an example to get you going. – ndugger May 20 '16 at 13:39
  • 2
    @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. – Daniel Dawes May 20 '16 at 13:50
  • @DanielDawes: There is nearly _always_ a better alternative available than `innerHTML`. – Cerbrus May 20 '16 at 13:52
  • @Cerbrus Sure, I'm not disputing that, but it's not helpful to OP if we don't give a reason why, and that also does not make `innerHTML` inherantly _bad_ – Daniel Dawes May 20 '16 at 13:54
  • The fact that setting content with innerHTML forces the browser to rebuild the DOM tree is inherently bad. – Cerbrus May 20 '16 at 13:55
  • @Cerbrus That would be incorrect. You could say the same about many _many_ other things. AngularJS is bad because the `$digest` cycle rebuilds the DOM. – Daniel Dawes May 20 '16 at 13:56
  • Well, since you put it like that, what more can I say! Thanks for the edits – Daniel Dawes May 20 '16 at 13:57
  • By the way, could you explain this code better? Im beginner, and i've problem with understand this code. – DiPix May 20 '16 at 14:31
  • 1
    @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. – ndugger May 20 '16 at 14:47
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";
}
ilosi
  • 11
  • 1
  • 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. – ndugger Mar 05 '19 at 16:52
  • i need this but with multiple buttons and i cannot figure it out – Dustin Angeletti Aug 05 '22 at 04:58
  • just like in the question example but instead of change the content, actually replace one div with another when the menu buttons are clicked – Dustin Angeletti Aug 05 '22 at 04:59
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')">
JTrixx16
  • 1,083
  • 9
  • 15
0

Try like this

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

Alex
  • 769
  • 1
  • 11
  • 18
-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>
Regis Portalez
  • 4,675
  • 1
  • 29
  • 41
-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

Community
  • 1
  • 1
user3617558
  • 45
  • 1
  • 5