Skip to content Skip to sidebar Skip to footer

Json.stringify An Array Of Html Elements/strings

How can we convert this Javascript Array [li.one, li.one, li.one, li.two, li.two, li.two] into a JSON array using JSON.stringify? Using the following Javascript: var stringsT

Solution 1:

$('.one, .two') returns a jQuery object containing references to whichever DOM elements have those two classes, it doesn't return an array of strings. So within your $.each(), the v parameter is not a string, it is a DOM element. If you want the HTML text (or just the text) of that element use $(v).html() or $(v).text():

var stringArray = [];
$('.one, .two').each(function(i, v) {
  stringArray.push( $(v).html() );
});
var jsonString = JSON.stringify(stringArray);

Demo: http://jsfiddle.net/stL1hz9t/

Note that I've used $('.one, .two').each() rather than the generic iterator $.each() method, because you want to loop over the items in a jQuery object. ($.each() will work, but it adds just that slight bit of extra complexity to your code.) You don't need your stringsToStringify variable (which as I mentioned above doesn't actually contain strings).

Or you can use the .map() method to simplify the code somewhat:

var stringArray = $('.one, .two').map(function (i, v) {
                    return $(v).html();
                  }).get();
var jsonString = JSON.stringify(stringArray);

Demo: http://jsfiddle.net/stL1hz9t/1/

Solution 2:

The array you created only returns jQuery object that reference the original DOM. To output the DOM element do the following:

$.each(stringsToStringify, function (i, v) {
    stringArray[i] = $("<p>").append($(v).clone()).html();
})

Note this whole $("<p>").append($(v).clone()).html() construction creates a clone of the original element, then appends the clone to a new parent and then gets the HTML from that. If you simply call .html() you will only get the content of the <li> tag, not the tag itself.

See fiddle here: http://jsfiddle.net/f0xchck6/

Post a Comment for "Json.stringify An Array Of Html Elements/strings"