bonaca bonaca - 4 months ago 11
jQuery Question

prevAll - how to get html instead object?

<span class='spant'>sky</span>
<span class='spant'>sea</span>
<span class='spant'>earth</span>
<span class='spant'>moon</span>


js

$(document).on('click', '.spant', function () {
var a = $(this).prevAll('.spant').addBack();
console.log(a);
localStorage.setItem('path', a);
});


click on span
earth
, for example.

console result:

[span.spant, prevObject: m.fn.init[0], context: span.spant]


localStorage result:

[object Object]


What I need is (console and localStorage):

<span class='spant'>sky</span><span class='spant'>sea</span><span class='spant'>earth</span>


Any help?

Answer

You can use Array#reduce to create a string of the outerHTML of the matched elements, either using get to get a true array from the jQuery object:

var html = a.get().reduce(function(html, element) {
  return html + element.outerHTML;
}, "");

...or by using reduce on the jQuery object:

var html = Array.prototype.reduce.call(a, function(html, element) {
  return html + element.outerHTML;
}, "");

Example of the first:

$(document).on('click', '.spant', function () {
    var a = $(this).prevAll('.spant').addBack();
    var html = a.get().reduce(function(html, element) {
      return html + element.outerHTML;
    }, "");
    console.log(html);
    //localStorage.setItem('path', html);
});
<span class='spant'>sky</span>
<span class='spant'>sea</span>
<span class='spant'>earth</span>
<span class='spant'>moon</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Or if you don't want to use reduce, a boring old loop:

var html = ""
a.each(function() {
  html += this.outerHTML;
});

Example:

$(document).on('click', '.spant', function () {
    var a = $(this).prevAll('.spant').addBack();
    var html = ""
    a.each(function() {
      html += this.outerHTML;
    });
    console.log(html);
    //localStorage.setItem('path', html);
});
<span class='spant'>sky</span>
<span class='spant'>sea</span>
<span class='spant'>earth</span>
<span class='spant'>moon</span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

...which I can't help but notice is both shorter and easier to understand. ;-)