2016-04-15 12 views
-3

最初のCSSクラスを選択するには.CategoryText<p>から発信しますか?jquery select parent css

<div class="CategoryText NoPadding"> 
    text 
</div> 

<div class="CategoryText NoPadding"> 
    <p>text</p> 
</div> 

-

$(".CategoryText > p").parent().parent().css({"display": "none",}); 

それは動作しません。これにより、ファーストクラス.CategoryTextからのすべての発信が選択されます。私は1つだけを選択したい - 最初のクラス.CategoryText

+3

ご質問は明確ではない。ここ

はデモです。それをより良く説明しよう。 – RRK

+0

あなたはどれを隠したいですか? – Vainglory07

+0

'CategoryText'にディスプレイnoneを追加しますか? – guradio

答えて

1

トライPREV()/()

$(".CategoryText > p").parent().prev('.CategoryText').css({"display": "none"}); 
+1

年ありがとう、それは動作します。 > https://jsfiddle.net/yLsynz0e/ prev()はキーワードです – Sebastian

4

これは、あなたが1あまりにも多くの.parent()を使用しているため、テキストのすべてが消えている次の$(".CategoryText:first-of-type")

https://jsfiddle.net/hjbj5do4/1/

2

最初のクラスを選択しますコール。また、jQueryにはの便利なメソッドが組み込まれており、display: noneが設定されています。

これを試してみてください:

$('.CategoryParent>p').parent().hide();

0

私はこの権利を得た場合は本当にわかりません。 したがって、.CategoryText > pは、すべてのp要素を、クラスCategoryTextの要素の直下の子要素として選択します。 :firstでは、最初に一致する要素のみを選択します。 次に、.parent()で親を選択すると、クラスCategoryTextを持つ要素が選択されます。

var e = $('.CategoryText > p:first').parent(); 
 
console.log(e.length + " mached element"); // only one matched item 
 
console.log(e.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script> 
 
<div class="CategoryText NoPadding"> 
 
    text 
 
</div> 
 

 
<div class="CategoryText NoPadding"> 
 
    <p>text 1</p> 
 
</div> 
 
<div class="CategoryText NoPadding"> 
 
    <p>text 2</p> 
 
</div>

0

は、あなたがそのようなクラスCategoryTextの最初の要素を選択することができます:$(".CategoryText:nth-child(1)")