我建議:
function n_siblings_same_tagname(node){
// Retrieve the tagName of the passed-in
// DOM node:
var elType = node.tagName;
// Converting the children the passed-node's
// parent's element children into an Array,
// using Array.from():
return Array.from(node.parentNode.children)
// filtering that array, using an Arrow
// which retains only those elements
// whose tagName is equal to the
// tagName of the passed-in elementary:
.filter(elem => elem.tagName == elType)
// finding the length of the filtered Array, and
// subtracting 1, as we want siblings not all
// elements of that type:
.length - 1;
}
或者,如果jQuery是首選:
function n_siblings_same_tagname(element){
// we may receive a jQuery object, or a DOM
// node; here we wrap the received element
// with jQuery:
var el = $(element);
// returning the length of the number of
// sibling elements matching the
// supplied selector, here the tagName
// of the passed in element, and
return el.siblings(el.prop('tagName')).length
}
鑑於OP的迴應,在下面的評論中,我會提供以下替代方案:
function n_siblings_same_tagname(element){
// we may receive a jQuery object, or a DOM
// node; here we wrap the received element
// with jQuery:
var el = $(element);
// returning the length of the number of
// child elements matching the selector
// provided by the tagName property
// of the passed-in element:
return el.parent().children(el.prop('tagName')).length
}
或者,修改後的JavaScript:
function n_siblings_same_tagname(node){
// Retrieve the tagName of the passed-in
// DOM node:
var elType = node.tagName;
// Converting the children the passed-node's
// parent's element children into an Array,
// using Array.from():
return Array.from(node.parentNode.children)
// filtering that array, using an Arrow
// which retains only those elements
// whose tagName is equal to the
// tagName of the passed-in elementary:
.filter(elem => elem.tagName == elType)
// finding the length of the filtered Array:
.length;
}
使用id =的DIV中的其他申報單 'some_random_id' 都是孩子,不是兄弟姐妹。你能否改變標題以反映這一點? – DinoMyte
是的,沒錯。我們對父元素一無所知。我們知道的只是一個指向子元素的指針,而其他子元素是元素的兄弟元素,我們知道 – user3600124
如果我們返回這些數字,那麼您不會檢索具有給定標籤名稱的兄弟的數量,您會發現所有帶有標籤名稱的孩子,兄弟姐妹加上原創。請你可以[編輯]你的問題,以確切地指定你想要的? –