Skip to content Skip to sidebar Skip to footer

Flip Divs Using A Function

I'm new with javascript and I have a tiny problem. I want to create a function and by pressing that button to invert the two divs ( the first one to be placed second and viceversa)

Solution 1:

Using pure javascript, you can simply switch the contents of each div:

functionflip(){
  div1_content = document.getElementById("div1").innerHTML;
  div2_content = document.getElementById("div2").innerHTML;
  
  document.getElementById("div1").innerHTML = div2_content;
  document.getElementById("div2").innerHTML = div1_content;
}
<divid="div1"> Text 1 </div><divid="div2"> Text 2 </div><buttononclick="flip()"> Flip it! </button>

We're simply storying the contents of each div, then assigning them to one another. Hopefully, you can take this, learn from it, and apply it how you intend to.

Solution 2:

Here is a simple javascript solution

jsFiddle https://jsfiddle.net/xzLme043/2/

myFunction = function(){
    var div1 = document.getElementById('one');
    var div2 = document.getElementById('two');

    var html = div1.innerHTML;
    div1.innerHTML = div2.innerHTML;
    div2.innerHTML = html;
};

Solution 3:

For this solution, you'll just place the current two divs in another parent div container, and then just insert the second div before the first, on the click of the invert button. No changing or pulling of inner text or HTML required.

functioninvertDivs(parentDiv) {
  var first = document.getElementById(parentDiv).firstElementChild;
  console.log(first);
  var second = document.getElementById(parentDiv).lastElementChild;
  console.log(second);
  document.getElementById(parentDiv).insertBefore(second, first);
}
<divid="parent"><divid="first">div 1</div><divid="second">div 2</div></div><buttononclick="invertDivs('parent');">invert</button>

Post a Comment for "Flip Divs Using A Function"