查询,排序和替换DOM元素

时间:2017-03-29 15:50:12

标签: javascript html dom

我正在尝试对我查询的nodeList的顺序进行排序,并将它们替换为DOM,但是使用下面的解决方案我在HTML中未定义。有谁知道最近发生了什么?

const container = elem[0].childNodes[1];
let graphs = container.querySelectorAll('visualization-container[data-graph]');

const sorted = [].slice.call(graphs).sort((a, b) => {
    const first = a.getAttribute('data-graph');
    const second = b.getAttribute('data-graph');

    return scope.visualizationsOrder[first] > scope.visualizationsOrder[second] ? 1 : -1;
});

console.log(sorted); // Sorted is correct
container.replaceWith(sorted); // error here

这是一个说明问题https://jsfiddle.net/ejdq1xyz/

的jsfiddle

1 个答案:

答案 0 :(得分:2)

此处的“问题”是,sortedNodes的数组。

我不太清楚你为什么要用它的分类子代替容器...
如果不应删除容器,则必须使用.appendChild().append().insertAdjacentElement()代替.replaceWith()

由于sorted是一个数组,您必须逐个添加for loop.forEach()的节点:

sorted.forEach(n => container.appendChild(n));
sorted.forEach(n => container.append(n));
sorted.forEach(n => container.insertAdjacentElement("beforeEnd", n));

如果是.append(),您还可以使用.apply()(ES5版本)或ES6 spread operator/syntax ...,因为它还会接受一组Nodes / {{3} }:

container.append.apply(container, sorted);
container.append(...sorted);

const order = {
  identifierOne: 4,
  identifierTwo: 3,
  identifierThree: 1,
  identifierFour: 2
};

const container = document.querySelector('.container');
const graphs = container.querySelectorAll('.graph[data-graph]');

const sorted = [].slice.call(graphs).sort((a, b) => {
    const first = a.getAttribute('data-graph');
    const second = b.getAttribute('data-graph');

    return order[first] > order[second] ? 1 : -1;
});

sorted.forEach(n => container.appendChild(n));
<div class='container'>
<div class='graph' data-graph='identifierOne'>4</div>
<div class='graph' data-graph='identifierTwo'>3</div>
<div class='graph' data-graph='identifierThree'>1</div>
<div class='graph' data-graph='identifierFour'>2</div>
</div>

如果应更换容器,则可以DOMStrings使用.replaceWith().apply()

container.replaceWith.apply(container, sorted);
container.replaceWith(...sorted);

const order = {
  identifierOne: 4,
  identifierTwo: 3,
  identifierThree: 1,
  identifierFour: 2
};

const container = document.querySelector('.container');
const graphs = container.querySelectorAll('.graph[data-graph]');

const sorted = [].slice.call(graphs).sort((a, b) => {
    const first = a.getAttribute('data-graph');
    const second = b.getAttribute('data-graph');

    return order[first] > order[second] ? 1 : -1;
});

container.replaceWith.apply(container, sorted);
//container.replaceWith(...sorted);
<div class='container'>
<div class='graph' data-graph='identifierOne'>4</div>
<div class='graph' data-graph='identifierTwo'>3</div>
<div class='graph' data-graph='identifierThree'>1</div>
<div class='graph' data-graph='identifierFour'>2</div>
</div>