bonaca bonaca - 4 months ago 9
HTML Question

How to get html of preceding elements

<span class='spanpath'>a</span>
<span class='spanpath'>b</span>
<span class='spanpath'>c</span>
<span class='spanpath'>d</span>
<span class='spanpath'>e</span>


js

$('.spanpath').click(function(){
var a = html of all preceding spans + html of clicked span
});


For example if
spanpath c
is clicked, result should be

<span class='spanpath'>a</span>
<span class='spanpath'>b</span>
<span class='spanpath'>c</span>


Any help?

Answer

Use preveAll() to get all the previous items, then use addBack() to include the item itself in the object.

$('.spanpath').click(function(){
  var a = $(this).prevAll('.spanpath').addBack();
  console.log(a.clone().wrapAll('<p>').parent().html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<span class='spanpath'>a</span>
<span class='spanpath'>b</span>
<span class='spanpath'>c</span>
<span class='spanpath'>d</span>
<span class='spanpath'>e</span>

Comments