818Swapping div elements with jQuery

I found myself in need for swapping div elements. On the one hand, elements, which are situated next to each other (in the code), on the other hand I also wanted to swap only sub-elements of these divs.

How can this be done with jQuery?

Let's start with the first case, swapping adjunct divs.

...
...
...
...
...
// get a handle on the elements
var elements = $(".elements");

// let's assume, we want to swap #e2 and #e3
var leftElement = $(elements[2]);
var rightElement = $(elements[3]);

leftElement.insertAfter(rightElement); // inserts leftElement after rightElement

insertAfter takes the object, with with the method is associated (leftElement) and inserts the object's div after the div specified as a method argument. Here's more on SO about it.

In a previous version of the code, i mistakenly though, that it's necessary to replace the leftElement with the right one prior to inserting...

// NG
leftElement.replaceWith(rightElement);
leftElement.insertAfter(rightElement);

This also seemed to work ok. Only later I found out, that any jQuery data() objects connected to the rightElement will get wiped when replaceWith is being called.

Finally you'll also want to do an update to the elements array, to get them in their new order:

var elements = $(".elements");

806Replacing HTML elements with jQuery’s replaceWith

Let's say you are having some HTML elements that should only be enabled, if the browser sports certain features. By default, the element is disabled, like in the following example:

Open File...

Next, we check in Javascript is this certain feature is supported. If it is, we replace the disabled element with an active version.

if (isSupported()) {
    $('#item').replaceWith('Open File...');
}

Which results in this:

Open File...

Simple, but effective.

647The 11G Text-Edit Challenge

Ok, here's a challenge. Say, you have a massive, 11 Gigabyte text file. The first two lines are the header files, unfortunately the header on line 2 is slightly wrong: Instead of 'Done' it should say 'Status:Done'. (Hit: 'Done' is the first occurrence of that string in that line)

Any Ideas?

  • split and the cat? Could not figure out to split it in uneven files, i.e. the first 2 lines and the rest...
  • vi? Seems to open, but bulks when saving it.

[Update]

sed seems to be the tool for this job. sed '2 s/Done/Status:Done/' input.txt > output.txt

Took about 7 minutes on my machine... Any better ideas still very much appreciated.

[Update 2: How to insert a tab with sed]

Inserting a tab with sed turned out to be more resilient than expected. Neither an escaped tab (\t) not a double-escaped tab (\t) seemed to do the trick. On bash it is necessary to drop out of sed and print the tab (\011) directly. 27 in the following statement means of course line 27.

sed '27 s/Done/Status:Done'"$(printf '\011')"'After Tab/' in.txt > out.txt