Получить все идентификаторы элементов после целевого элемента - PullRequest
0 голосов
/ 25 декабря 2018

Так как я могу получить все элементы после целевого элемента, например, я хочу получить все элементы после вызова идентификатора c, независимо от количества элементов после c

Например,

d
e
f

и я хочу вывести результат в выводе вызова элемента id

Это мой код, на котором я застрял

/*
Get all the elements ids after the id call c and output those 
ids in the id call output 

For example 
document.querySelector('#output').innerHTML = ??;

How?
*/
#output{
  color: red;
}
<h1 id='a' class='letters'>A</h1>
<h1 id='b' class='letters'>B</h1>
<h1 id='c' class='letters'>C</h1>
<h1 id='d' class='letters'>D</h1>
<h1 id='e' class='letters'>E</h1>
<h1 id='f' class='letters'>F</h1>

<h1 id='output'></h1>

Ответы [ 4 ]

0 голосов
/ 26 декабря 2018

Не обижайте другие примеры здесь, но я заметил, что некоторые примеры кода здесь будут иметь некоторые проблемы с совместимостью в определенных браузерах, таких как

IE 11, так что это работает на всех основных браузерах, на которых я это тестировал.На всякий случай, если вы пытаетесь заставить это работать на IE 11, вот мой пример ...

var afterC = [].slice.call(document.querySelectorAll('#c ~ *.letters')).map(function(elem){ return elem.getAttribute('id');});

document.querySelector('#output').innerHTML = afterC;
#output{
  color: red;
}
<h1 id='a' class='letters'>A</h1>
<h1 id='b' class='letters'>B</h1>
<h1 id='c' class='letters'>C</h1>
<h1 id='d' class='letters'>D</h1>
<h1 id='e' class='letters'>E</h1>
<h1 id='f' class='letters'>F</h1>

<h1 id='output'></h1>
0 голосов
/ 25 декабря 2018

Вы можете использовать document.querySelectorAll('#c ~ .letters'), который использует общий братский комбинатор :

document.querySelector('#output').innerHTML = Array.from(
  document.querySelectorAll('#c ~ .letters')
).map(element => element.textContent).join(' ');
#output{
  color: red;
}
<h1 id='a' class='letters'>A</h1>
<h1 id='b' class='letters'>B</h1>
<h1 id='c' class='letters'>C</h1>
<h1 id='d' class='letters'>D</h1>
<h1 id='e' class='letters'>E</h1>
<h1 id='f' class='letters'>F</h1>

<h1 id='output'></h1>
0 голосов
/ 25 декабря 2018

Один из возможных способов:

// using a named function, passing in a CSS selector:
let getAllAfter = function(selector) {

  // here we return the result of document.querySelectorAll(),
  // after using Array.from() to convert the Array-like NodeList
  // to an Array:
  return Array.from(
    document.querySelectorAll(
      // using the passed-in selector and concatenating that
      // with the general sibling combinator ('~') and, in this
      // case using '.letters' to restrict the selector to elements
      // containing that class:
      selector + '~ .letters')
  );
}

// setting the textContent of the element with the id of 'output'
// to be equal to the Array of elements - having mapped
// their textContent using Array.prototype.map(), and joining
// the resulting Array using Array.prototype.join():
document.getElementById('output').textContent = getAllAfter('#c').map(el => el.textContent).join(', ');
#output {
  color: red;
}
<h1 id='a' class='letters'>A</h1>
<h1 id='b' class='letters'>B</h1>
<h1 id='c' class='letters'>C</h1>
<h1 id='d' class='letters'>D</h1>
<h1 id='e' class='letters'>E</h1>
<h1 id='f' class='letters'>F</h1>

<h1 id='output'></h1>

Это, конечно, использование жестко закодированного селектора, который не особенно полезен в различных контекстах, поэтому измените вышеупомянутую функцию, чтобы принятьвторой селектор, чтобы ограничить выбранные последующие братья и сестры селектором:

// using a named function, passing in a CSS selector:
let getAllAfter = function(targetSelector, siblingSelector) {

  // here we return the result of document.querySelectorAll(),
  // after using Array.from() to convert the Array-like NodeList
  // to an Array:
  return Array.from(
    document.querySelectorAll(
      // using the passed-in selector and concatenating that
      // with the general sibling combinator ('~') and, in this
      // case using '.letters' to restrict the selector to elements
      // containing that class:
      targetSelector + ' ~ ' + siblingSelector)
  );
}

// setting the textContent of the element with the id of 'output'
// to be equal to the Array of elements - having mapped
// their textContent using Array.prototype.map(), and joining
// the resulting Array using Array.prototype.join():
document.getElementById('output').textContent = getAllAfter('#c', '.letters').map(el => el.textContent).join(', ');
#output {
  color: red;
}
<h1 id='a' class='letters'>A</h1>
<h1 id='b' class='letters'>B</h1>
<h1 id='c' class='letters'>C</h1>
<h1 id='d' class='letters'>D</h1>
<h1 id='e' class='letters'>E</h1>
<h1 id='f' class='letters'>F</h1>

<h1 id='output'></h1>

Конечно, в совместимых браузерах мы могли бы избежать объединения строк и просто использовать шаблонный литерал для преобразования предоставленных строк в селектор:

// using a named function, passing in a CSS selector:
let getAllAfter = function(targetSelector, siblingSelector) {

  // here we return the result of document.querySelectorAll(),
  // after using Array.from() to convert the Array-like NodeList
  // to an Array:
  return Array.from(
    document.querySelectorAll(
      // using the passed-in selector and concatenating that
      // with the general sibling combinator ('~') and, in this
      // case using '.letters' to restrict the selector to elements
      // containing that class:
      `${targetSelector} ~ ${siblingSelector}`)
  );
}

// setting the textContent of the element with the id of 'output'
// to be equal to the Array of elements - having mapped
// their textContent using Array.prototype.map(), and joining
// the resulting Array using Array.prototype.join():
document.getElementById('output').textContent = getAllAfter('#c', '.letters').map(el => el.textContent).join(', ');
#output {
  color: red;
}
<h1 id='a' class='letters'>A</h1>
<h1 id='b' class='letters'>B</h1>
<h1 id='c' class='letters'>C</h1>
<h1 id='d' class='letters'>D</h1>
<h1 id='e' class='letters'>E</h1>
<h1 id='f' class='letters'>F</h1>

<h1 id='output'></h1>

Список литературы:

0 голосов
/ 25 декабря 2018

Получите позицию c, затем возьмите все h1s, которые следующие:

 const c = document.querySelector("#c");
 const h1s = [...document.querySelectorAll("h1")];
 const position = h1s.indexOf(c);

 const result = h1s.filter((_, i) => i > position);

  for(const entry of result)
    output.appendChild(entry.cloneNode(true));
...