简体   繁体   English

如何通过文字获得兄弟姐妹?

[英]How to get siblings by text?

I can't seem to figure out how to get a sibling element by text. 我似乎无法弄清楚如何通过文本获得兄弟元素。 This is what I currently have: 这就是我目前拥有的:

var elem = $('div');
var e = elem.siblings('.condition').contains('text');

jQuery has no contains() method which works as you expect it to. jQuery没有contains()方法,它可以按预期工作。 Instead you need to use the :contains selector. 相反,您需要使用:contains选择器。 Try this: 尝试这个:

var $elem = $('div');
var $e = elem.siblings('.condition:contains("text")');
console.log($e.length); // will be greater than 0 if an element was matched

You can also concatenate a variable in the selector if required: 如果需要,您还可以在选择器中连接变量:

var foo = 'bar';
var $e = $elem.siblings('.condition:contains("' + foo + '")');

And as suggested by @DavidThomas you could use filter() : 正如@DavidThomas所建议的那样你可以使用filter()

var $e = $elem.siblings().filter(function() {
    return $(this).text() == 'text';
});

the :contains selector should do everything you need: :contains包含选择器应该做你需要的一切:

var elem = $('div');
elem.siblings(".condition:contains('text')");

$('div').siblings(':contains("text here")');

http://codepen.io/anon/pen/obodJB

As you posted this question with both JavaScript and jQuery tags, I thought I'd take the time to offer a JavaScript solution (although you've already accepted a jQuery solution). 当您使用JavaScript和jQuery标签发布此问题时,我认为我会花时间提供JavaScript解决方案(尽管您已经接受了jQuery解决方案)。 Bearing in mind this is currently restricted, realistically, to those browsers incorporating ECMAScript 6: 请记住,目前这对于包含ECMAScript 6的浏览器来说是现实的限制:

// 'start' : Node, NodeList, HTMLCollection, Array of Nodes
//           The nodes whose siblings you're searching for
// 'needle': String, the text-content you're looking to select
//           sibling nodes by.

function getSiblingsByTextContent(start, needle) {

  // converting the supplied start variable into an Array:
  var allStarts = Array.from(start),

  // Using the spread operator ('...') to create a new Set
  // of the unique array elements from the new array
  // formed from Array.prototype.map(); here we use
  // an Array function to return the parentNode of n (the
  // node from the allStarts Array):
    uniqueParents = [...new Set(allStarts.map(n => n.parentNode))],

    // here we iterate over the uniqueParents Array, and form
    // a new Array, using Array.prototype.map() again:
    allSiblings = uniqueParents.map(function(n) {
    // n is the current array-element from the array
    // over which we're iterating.

    // converting the children of the node, using
    // Array.prototype.filter():
      return Array.from(n.children).filter(function(nc) {
      // here we keep only those nodes (here 'nc') that
      // are not contained within the AllStarts array, and
      // whose textContent contains the needle we're searching for:
        return allStarts.indexOf(nc) === -1 && nc.textContent.match(needle);
      });
      // we reduce the returned array of arrays, with
      // Array.prototype.reduce, combining each Array
      // element with the array that precedes it,
      // intialising with an Array literal ('[]')
    }).reduce((a,b) => a.concat(b), []);

    // and returning the found-siblings to the calling
    // context:
  return allSiblings;
}

// calling the named function, suppling a NodeList of
// span elements found in the document, searching for
// siblings containing the '-' character:
getSiblingsByTextContent(document.querySelectorAll('span'), '4')
// as the function returns an Array we can iterate over that
// Array using Array.prototype.forEach() to add a new
// class to each element's classList to show the found-
// siblings:
.forEach(n => n.classList.add('found'));

 // 'start' : Node, NodeList, HTMLCollection, Array of Nodes // The nodes whose siblings you're searching for // 'needle': String, the text-content you're looking to select // sibling nodes by. function getSiblingsByTextContent(start, needle) { // converting the supplied start variable into an Array: var allStarts = Array.from(start), // Using the spread operator ('...') to create a new Set // of the unique array elements from the new array // formed from Array.prototype.map(); here we use // an Array function to return the parentNode of n (the // node from the allStarts Array): uniqueParents = [...new Set(allStarts.map(n => n.parentNode))], // here we iterate over the uniqueParents Array, and form // a new Array, using Array.prototype.map() again: allSiblings = uniqueParents.map(function(n) { // n is the current array-element from the array // over which we're iterating. // converting the children of the node, using // Array.prototype.filter(): return Array.from(n.children).filter(function(nc) { // here we keep only those nodes (here 'nc') that // are not contained within the AllStarts array, and // whose textContent contains the needle we're searching for: return allStarts.indexOf(nc) === -1 && nc.textContent.match(needle); }); // we reduce the returned array of arrays, with // Array.prototype.reduce, combining each Array // element with the array that precedes it, // intialising with an Array literal ('[]') }).reduce((a, b) => a.concat(b), []); // and returning the found-siblings to the calling // context: return allSiblings; } // calling the named function, suppling a NodeList of // span elements found in the document, searching for // siblings containing the '-' character: getSiblingsByTextContent(document.querySelectorAll('span'), '4') // as the function returns an Array we can iterate over that // Array using Array.prototype.forEach() to add a new // class to each element's classList to show the found- // siblings: .forEach(n => n.classList.add('found')); 
 div div::before, div span::before { content: '( '; } div div::after, div span::after { content: ' )'; } .found { font-weight: bold; color: limegreen; } 
 <div> <span>1 - span</span> <span>2 - span</span> <span>3 - span</span> <div>4 - div</div> <span>5 - span</span> <span>6 - span</span> <span>7 - span</span> </div> <div> <span>8 - span</span> <span>9 - span</span> <span>10 - span</span> <div>11 - div</div> <span>12 - span</span> <span>13 - span</span> <span>14 - span</span> </div> 

JS Fiddle demo . JS小提琴演示

References: 参考文献:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM