7

So let's assume that I have a set of nested divs:

<div id="likelyToBeCalled">
    <div id="likelyOddHeader" class="row">
        <div id="likelyOddA" class="left" name="test1">Test1</div>
        <div id="LikelyOddB" class="middle"><img src="image002.png"/></div>
        <div id="timeZone" class="right">West</div>
    </div>

and further down the page:

<div id="unlikelyToBeCalled">
    <div id="likelyOddHeader" class="row">
        <div id="likelyOddA" class="left">Test2</div>
        <div id="LikelyOddB" class="middle"><img src="image002.png"/></div>
        <div id="timeZone" class="right">West</div>
    </div>

How would I move Test1 to "unlikelyToBeCalled". I've been trying this with a form / submit button just for kicks, here's the code for that:

<script type="text/javascript">
    function doSubmit() {
        document.getElementById('unlikelyToBeCalled').appendChild(
            document.getElementsByTagName('Test1')
        );
    }
</script>
<br /><br /><br />
<form method="POST" action="file:///C:/wamp/www/index.html" id="submitform" name="submitform">
    <input type="submit" name="Submit" value="Move divs" onClick="doSubmit()"  />
</form>

Or something to that effect. Any help would rock

VisioN
  • 143,310
  • 32
  • 282
  • 281
HunderingThooves
  • 962
  • 8
  • 20
  • 33
  • You tagged [tag:jquery] but your code is in pure javascript, how do you want answer? – Wirone Jun 05 '12 at 21:54
  • `action="file:///C:/wamp/www/index.html"` --- this looks wrong – zerkms Jun 05 '12 at 21:56
  • Here are a couple of other StackOverflow answers: [Jquery]: http://stackoverflow.com/questions/1279957/how-to-move-an-element-into-another-element, [Pure JS]: http://stackoverflow.com/questions/3415480/moving-a-div-element-to-bottom-of-parent-as-last-child – jwatts1980 Jun 05 '12 at 21:57
  • 1
    Also, your example html contains duplicate ID's. – Kevin B Jun 05 '12 at 21:58

2 Answers2

9

Use .appendTo()

$('#likelyOddA').appendTo('#unlikelyToBeCalled')
Musa
  • 96,336
  • 17
  • 118
  • 137
  • 3
    You don't have to detach it, `appendTo` will automagically remove it from it's previous location. – Kevin B Jun 05 '12 at 21:59
  • 1
    do not forget the prepentTo if you want to insert it in the beginning instead of end – Iman Jan 29 '15 at 08:36
5

If I understand what you want:

$('div[name=test1]').appendTo('#unlikelyToBeCalled');

getElementsByTagName('Test1') will not get element with name="Test1", it is supposed to, for example, get all divs (with code getElementsByTagName('div') of course). Next, you have used #likelyOddHeader and other ids twice, but id must be unique.

Wirone
  • 3,304
  • 1
  • 29
  • 48