1

ここで明らかなことを見逃しているかどうかはわかりませんが、これを解決しようとしてスピンしました。

コンテナーの最初の子を見つけて、その要素またはクラスを返し、それを使用して、そのコンテナー内の他の最上位の一致する要素を取得したいと考えています。

例えば

<div class="box">
    <a href="#">The First Element</a>
    <div><p> some content with a <a href="#">link that should not be included</a></div>
    <h2>a heading</h2>
    <p>this is some content</p>
    <a href="#">This link should be found by the search</a>
</div>

したがって、jQuery を使用して最初の子 (この場合は「a」タグ) を調べ、一致する要素を検索したいと思います。直接の子孫のみを取得したいのですが、アイデアはありますか?

EDIT : すばらしい回答をありがとう - 私が最初に見逃したのは .prop メソッドだったと思います。いくつかのソリューションをテストして、どれが最適かを確認する必要があります....更新は近日公開予定です。

4

5 に答える 5

1

少しわかりにくいので、ここにいくつかのオプションを示します。最初のいくつかを示すために、背景のライムをオンにします。

その最初のリンクのすべての兄弟は、次のようになります。

$('a:first').siblings().css('background-color', 'lime');

ボックス内の最初の要素のすべての兄弟:

$('.box>:first').siblings().css('background-color', 'lime');

aボックス内の最初の要素のすべての兄弟

$('.box>:first(a)').siblings().css('background-color', 'lime');

さて、もう少し複雑な、この最初の要素に一致するもの:

$('.box>:first').each(function () {
  //if it has a single class we can do this
  var myclass = '.' + $(this).attr('class');
  // use that single class above
  $(this).siblings(myclass).css('background-color', 'blue');

  //find elements with the same tag that are siblings of my element
  $(this).siblings(this.tagName).css('background-color', 'lime');

  //handle multiple classes
  var myclassAll = $(this).attr('class');

  //split the multiple classes, then use it
  var myclassList = myclassAll.split(" ");
  $(this).siblings().each(function () {
    var iam = $(this);// each sibling
    $.each(myclassList, function (i) {
      if (iam.hasClass(myclassList[i])) {
        iam.addClass(myclassList[i] + 'New');//add new class on matches
      }
    });
  });
});
于 2013-01-08T14:44:16.830 に答える
1
var $box = $('.box'), 
    $first = $box.children().first(),
    type = $first.prop('localName'),
    $matching = $box.children(type);

http://jsfiddle.net/X8hgP/

于 2013-01-08T13:31:56.073 に答える
0

これを見てください - http://jsfiddle.net/xyK72/

var selectedElement = $('.box > :first-child').prop('tagName');
$('.box > :first-child').siblings(selectedElement).addClass('highlight');

子孫ではなく兄弟を探していることに注意してください。

于 2013-01-08T13:43:58.230 に答える
0
var first_element = $(".box *:first-child").prop("tagName");
alert( first_element  );

注 >>> *:first-childセレクターから最初の HTML タグを取得します

于 2013-01-08T13:45:38.337 に答える
0
var fc= jQuery(".box>:first-child").eq(0); //is the first child of container
var allE = fc.parent().children(fc.prop("tagName")); //contains all elements with tagname equal to fc's
于 2013-01-08T13:38:58.103 に答える