Array of string elements

Asked

Viewed 109 times

2

How to transform this Object array from td's

localidades = "<td style='white-space: nowrap;'>Sto.amaro</td><td style='white-space: nowrap;'>Osasco</td><td style='white-space: nowrap;'>Lapa</td><td style='white-space: nowrap;'>Osasco Ii</td><td style='white-space: nowrap;'>Sao Miguel</td><td style='white-space: nowrap;'>Pirituba</td><td style='white-space: nowrap;'>Santana</td>";

then I use

console.log($(localidades).text(''));

and it returns me this array below

[<td style=​"white-space:​ nowrap;​">​​</td>​, <td style=​"white-space:​ nowrap;​">​​</td>​, <td style=​"white-space:​ nowrap;​">​​</td>​, <td style=​"white-space:​ nowrap;​">​​</td>​, <td style=​"white-space:​ nowrap;​">​​</td>​, <td style=​"white-space:​ nowrap;​">​​</td>​, <td style=​"white-space:​ nowrap;​">​​</td>​]

I would like to turn this array back to string only with empty tds as in the string below

"<td style='white-space: nowrap;'></td><td style='white-space: nowrap;'></td><td style='white-space: nowrap;'></td><td style='white-space: nowrap;'></td><td style='white-space: nowrap;'></td><td style='white-space: nowrap;'></td><td style='white-space: nowrap;'></td>"
  • The first array is valid (afaik), so there is no way. Unless it is an array of references to DOM elements. Proceed?

  • Did you manage to solve this question?

2 answers

2


You can use the function .each concatenating the HTML of the element into a variable:

var $localidades = $("<td style='white-space: nowrap;'>Sto.amaro</td><td style='white-space: nowrap;'>Osasco</td><td style='white-space: nowrap;'>Lapa</td><td style='white-space: nowrap;'>Osasco Ii</td><td style='white-space: nowrap;'>Sao Miguel</td><td style='white-space: nowrap;'>Pirituba</td><td style='white-space: nowrap;'>Santana</td>");

$localidades.text('');

var html = "";
$localidades.each(function(i, elm) {
  html += elm.outerHTML;
});

$("#result").text(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result">
</div>

1

If you want to have a string with these empty Tds you can do so to empty them:

$(localidades).map(function(){
    this.innerHTML = '';
    return this;
});

but then you need a dummy element to have that HTML and you can extract it into a string. An example would be:

var limpo = $(localidades).map(function () {
    this.innerHTML = '';
    return this;
});
var tr = $('<tr />').html(limpo);
alert(tr[0].innerHTML);

jsFiddle: http://jsfiddle.net/2woqp6tu/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.