joe
joe

Reputation: 1135

How to remove the unnecessary html after appending?

var split = $('.split-locations').text().split('\n');
for (var i = 0; i < split.length; i++) {
   $('.split-locations').append("<pre>"+split[i]+"</pre>");
}

<div class="split-location">
Singapore
USA
Aussie
</div>

On profile, the user type with enter for each address, but the problem is when it is saved, the addresses would be displayed on the webpage as:

Singapore USA Aussie
<pre>Singapore</pre>
<pre>USA</pre>
<pre>Aussie</pre>

I am not sure why the text (Singapore USA Aussie) is still there. Only wanted to display:

<pre>Singapore</pre>
<pre>USA</pre>
<pre>Aussie</pre>

How to remove the first line before <pre> bunch? Or how to replace text with pre bunch?

Update

One more thing: how to print first array outside loop because need to display first one outside loop and then put the rest of array inside accordion? Here the code is: for you to understand what I am trying to do. see the comment.

 var location = $('.split-locations');
    var split = $('.split-locations').text().split('\n');
    location.empty();
    //need to print first location

    location.append('<div class="accordion-location">');
    for (var i = 0; i < split.length; i++) {
      //print remaining location after minus first location
       location.append("<pre>"+split[i]+"</pre>");
    }
    location.append('</div>');
    });

Upvotes: 2

Views: 53

Answers (2)

N-ate
N-ate

Reputation: 6926

You need to clear out the location:

var split = $('.split-locations').text().split('\n');
$('.split-locations').empty();
for (var i = 0; i < split.length; i++) {
   $('.split-locations').append("<pre>"+split[i]+"</pre>");
}

Update:

var $el = $('<div class="accordion-location"></div>');
for (var i = 0; i < split.length; i++) {
   $el.append("<pre>"+split[i]+"</pre>");
}
location.append($el);

Upvotes: 1

Alexander O&#39;Mara
Alexander O&#39;Mara

Reputation: 60527

You need to empty the container element before appending the pre nodes. Try this.

var split = $('.split-locations').text().split('\n');
$('.split-locations').empty();
for (var i = 0; i < split.length; i++) {
   $('.split-locations').append("<pre>"+split[i]+"</pre>");
}

Upvotes: 2

Related Questions