https://jsfiddle.net/jqb816a1/5/
我想這幾個不同的解決方案。起初,我認爲DOM元素的基本向上遍歷是可行的,但不幸的是,既然你在你的問題中指定了你希望它也通過未知數目的父元素的兄弟姐妹,我無法完全理解牛仔舞。
我最終創建了一個包含Set Object
的對象以保存所有這些文本節點,並且getPrev
方法在給定包含頁面上的文本節點的元素時將返回以前的文本節點。在這種情況下,你span
標籤與carot
的設置
function findTextNodes(node) {
let text_node_set = new Set();
traversal(node);
function traversal(node) {
check_for_text(node);
let ele = node.nextSibling;
while (ele) {
check_for_text(ele);
ele = ele.nextSibling;
}
}
function check_for_text(ele) {
if (ele.childNodes) {
for (let child of ele.childNodes) {
if (child.nodeType == 3 && new RegExp(/\S/g).test(child.textContent)) {
text_node_set.add(child);
} else {
traversal(child);
}
}
}
}
return {
getPrev: function(ele_node) {
let text_node;
if (ele_node.childNodes) {
for (let child of ele_node.childNodes) {
if (child.nodeType == 3 && new RegExp(/\S/g).test(child.textContent)) {
text_node = child;
}
}
}
if (this.text_node_set.has(text_node)) {
let prev, previousNode;
this.text_node_set.forEach(function(node) {
if (node === text_node) {
if (prev) previousNode = prev;
}
prev = node;
})
return previousNode;
}
},
text_node_set
}
}
使用返回對象的ID:
let text_nodes = findTextNodes(document.body);
// object: text_nodes
// methods: getPrev
// properties: text_node_set
let caret = document.getElementById('carot');
//print the previous node to the console
console.log(text_nodes.getPrev(carot));
//or turn its text green
let prevNode = text_nodes.getPrev(carot);
//(we need to grab the parent node of the text for styling)
prevNode.parentNode.style.color = "lightGreen";
可以使用獲得的'#caret'兄弟文本['Node.nextSibling'](https://developer.mozilla.org/en-US/docs/Web/API/Node/nextSibling)並減去它的編號。然後使用'$(*:contains(newNum)「)選擇元素的號碼等於新號碼。' – Mohammad
當然,在文本節點上調用'css'不太可能做太多...... –