jQuery:相同标签名称的兄弟姐妹的数量

时间:2016-07-07 21:55:12

标签: jquery

这里我遇到了一个jQuery问题。考虑这个随机元素:

<div id="some_random_id">
  <b></b>
  <div></div>
  <b></b>
  <div></div>
  <div></div>
</div>

我们所拥有的只是指向子元素的指针。我们对父元素一无所知。我们需要编写一个函数,输出相同标签名称的兄弟NUMBER。

function n_siblings_same_tagname(this){};

当我们的对象是DIV标记名时,函数必须返回2;当标记名是B时,函数必须返回1.我们如何做到这一点?感谢

2 个答案:

答案 0 :(得分:3)

这应该选择父母的所有孩子使用相同的标签:

function n_siblings_same_tagname(element){
    element = $(element);
    return element.parent().children(element.prop("tagName")).length;
};    

答案 1 :(得分:3)

我建议:

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;
}