1

I'm having a little difficulty trying to switch 2 elements around with Jquery when they are inside a string variable.

eg:

var myString = 
              "<div class='chatMessage'>Something here 
               <div class='test'>My test</div>
               <div class='anotherTest'> the other test</div>
               Something there
               </div>";

What I would like is to switch the two classes around, making "anotherTest" be infront of "test".

What I've tried so far is:

var myString = 
              "<div class='chatMessage'>Something here 
               <div class='test'>My test</div>
               <div class='anotherTest'> the other test</div>
               Something there
               </div>";

var div1 = myString.filter('.test');
var div2 = myString.filter('.anotherTest');

var tdiv1 = div1.clone();
var tdiv2 = div2.clone();

myMessage = div1.replaceWith(tdiv2);
myMessage = div2.replaceWith(tdiv1);

However I receive the following error

t.replace is not a function

I was wondering how I would be able to achieve to switch the two divs around while still stored inside the variable before displaying it to the user?

killstreet
  • 1,251
  • 2
  • 15
  • 37

2 Answers2

2

You're making things harder on yourself by adding the constraint that this needs to be done by direct string manipulation. HTML is meant to be rendered into the DOM -- and since that's a "document object model" it stands to reason it's better-suited for modelling your document as objects.

jQuery may seem a bit old-hat, but its whole purpose is to make querying the DOM easier, so it works well here. All you need to do is parse the string, query the node you want to move, and insert it before the element you want it in front of. You can get the HTML back using $.fn.html(), or you could just leave as an element if you're going to insert it somewhere on your page.

var $el = $(myString);
$('.anotherTest', $el).insertBefore($('.test', $el));
var myMessage = $el.html();

jsfiddle here

Josh from Qaribou
  • 6,776
  • 2
  • 23
  • 21
0

Try this one. Just split the string by "</div>", it will make an array of splited contents, then re-add "</div>" to each splited string (this will be consumed in the process of splitting). Then reassemble.

https://jsfiddle.net/8a4wgn7k/

var myString = "<div class='test'>My test</div><div class='anotherTest'> the other test</div>";


var res = myString.split("</div>");
res[0] +="</div>";
res[1] +="</div>";
var switchedString=res[1]+res[0]
Zorak
  • 709
  • 7
  • 24