Jessica Jessica - 5 months ago 19
HTML Question

Select Range of Dom Elements

I'm trying to select a range of dom elements, from

element
until
element
. That's achievable in JQuery like this: (Source)

$('#id').nextUntil('#id2').andSelf().add('#id2')


I'm trying to achieve that using JavaScript ONLY.

Here's what I tried, but I get a infinite loop:

function prevRange(element, prevTill) {
var result = [];

while (element !== prevTill)
result.push(element);
return result;
}


JSFiddle





var wrapper = document.getElementById('wrapper'),
wrapperChildren = wrapper.children;

console.log(prevRange(wrapperChildren[2], wrapperChildren[0]));

function prevRange(element, prevTill) {
var result = [];

/*while (element !== prevTill)
result.push(element);*/
return result;
}

<ul id="wrapper">
<li class="inner">I'm #01</li>
<li class="inner">I'm #02</li>
<li class="inner">I'm #03</li>
<li class="inner">I'm #04</li>
</ul>




Answer

Use Element.previousElementSibling:

var wrapper = document.getElementById('wrapper'),
  wrapperChildren = wrapper.children;

console.log(prevRange(wrapperChildren[2], wrapperChildren[0]));

function prevRange(element, prevTill) {
  var result = [element];

  while (element && element !== prevTill) {
    element = element.previousElementSibling;
    result.push(element);
  }

  return result;
}
<ul id="wrapper">
  <li class="inner">I'm #01</li>
  <li class="inner">I'm #02</li>
  <li class="inner">I'm #03</li>
  <li class="inner">I'm #04</li>
</ul>

Comments