Flip divs using a function

时间:2015-07-28 16:24:51

标签: javascript 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). I hope you understand.

I have this code:

<div> text 1 </div>
<div> text 2 </div>
<button> invert </button>

3 个答案:

答案 0 :(得分: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.

答案 1 :(得分: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;
};

答案 2 :(得分: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>