-1

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). I hope you understand.

I have this code:

<div> text 1 </div>
<div> text 2 </div>
<button> invert </button>
Ionny
  • 3
  • 1
  • What javascript do you have so far? – code Jul 28 '15 at 16:25
  • 2
    *You* want to "create a function"? Or you want *someone else* to "create a function"? – Wes Foster Jul 28 '15 at 16:27
  • Well, I know the code doesn't include javascript, that's why I want to create a javascript function. That is the only code I have. I tried with reverse, but it doesn't seem to be working – Ionny Jul 28 '15 at 16:28
  • Wes, I just want a hint, I didn't ask for someone to create it. As I said, I;m trying to learn. I've done a few functions, but this one kinda bugs me. – Ionny Jul 28 '15 at 16:30
  • Thank you all for your answers. I will try every example – Ionny Jul 28 '15 at 16:40

3 Answers3

2

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

function flip(){
  div1_content = document.getElementById("div1").innerHTML;
  div2_content = document.getElementById("div2").innerHTML;
  
  document.getElementById("div1").innerHTML = div2_content;
  document.getElementById("div2").innerHTML = div1_content;
}
<div id="div1"> Text 1 </div>
<div id="div2"> Text 2 </div>
<button onclick="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.

Wes Foster
  • 8,770
  • 5
  • 42
  • 62
1

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;
};
Canvas
  • 5,779
  • 9
  • 55
  • 98
1

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.

function invertDivs(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);
}
<div id="parent">
  <div id="first">div 1</div>
  <div id="second">div 2</div>
</div>
<button onclick="invertDivs('parent');">invert</button>
Honinbo Shusaku
  • 1,411
  • 2
  • 27
  • 45