developer tip

주어진 클래스 이름으로 첫 번째, 두 번째 또는 세 번째 요소를 선택하는 방법은 무엇입니까?

optionbox 2020. 11. 8. 09:46
반응형

주어진 클래스 이름으로 첫 번째, 두 번째 또는 세 번째 요소를 선택하는 방법은 무엇입니까?


요소 목록에서 특정 요소를 어떻게 선택할 수 있습니까? 다음이 있습니다.

<div class="myclass">my text1</div>
<!-- some other code follows -->
<div>
    <p>stuff</p>
</div>
<div>
    <p>more stuff</p>
</div>
<p>
    <span>Hello World</span>
</p>
<div class="myclass">my text2</div>
<!-- some other code follows -->
<div>
    <p>stuff</p>
</div>
<p>
    <span>Hello World</span>
</p>
<input type=""/>
<div class="myclass">my text3</div>
<!-- some other code follows -->
<div>
    <p>stuff</p>
</div>
<footer>The end</footer>

div.myclass {doing things}분명히 모두에게 적용되는 CSS 클래스 가 있지만 마크 업의 위치에 관계없이.myclass 이와 같이 클래스의 첫 번째, 두 번째 또는 세 번째 div를 선택할 수 있기를 원했습니다 .

div.myclass:first {color:#000;} 
div.myclass:second {color:#FFF;} 
div.myclass:third {color:#006;}

.eq( index )현재 사용하고 있는 jQuery 인덱스 선택과 거의 비슷 하지만 스크립트가없는 대안이 필요합니다.

구체적으로 말하자면, 다른 클래스를 추가하거나 ID를 사용하여 작업하는 것과 같은 것이 아닌 의사 선택기를 찾고 있습니다.


이 질문을 게시하고 오늘 사이에 마침내 이것을 깨달았을 것입니다. 그러나 선택기의 특성 때문에 계층 적으로 관련이없는 HTML 요소를 탐색하는 것이 불가능합니다.

또는 간단히 말하면, 귀하의 의견에서

균일 한 부모 컨테이너가 없습니다.

... 다른 답변에서 볼 수 있듯이 어떤 식 으로든 마크 업을 수정하지 않고 선택자만으로는 불가능합니다.

당신 JQuery와 사용하는 .eq()솔루션을.


nth-child (항목 번호) EX 사용

<div class="parent_class">
    <div class="myclass">my text1</div>
    some other code+containers...

    <div class="myclass">my text2</div>
    some other code+containers...

    <div class="myclass">my text3</div>
    some other code+containers...
</div>
.parent_class:nth-child(1) { };
.parent_class:nth-child(2) { };
.parent_class:nth-child(3) { };

또는

: nth-of-type (항목 번호) 코드와 동일

.myclass:nth-of-type(1) { };
.myclass:nth-of-type(2) { };
.myclass:nth-of-type(3) { };

예, 할 수 있습니다. 예를 들어, 테이블의 다른 열을 구성하는 td 태그의 스타일을 지정하려면 다음과 같이 할 수 있습니다.

table.myClass tr > td:first-child /* First column */
{
  /* some style here */
}
table.myClass tr > td:first-child+td /* Second column */
{
  /* some style here */
}
table.myClass tr > td:first-child+td+td /* Third column */
{
  /* some style here */
}

이것은 대답이 아닌 것만 큼 대답이 아닙니다. 즉, 위에서 투표율이 높은 대답 중 하나 가 실제로 잘못된 이유를 보여주는 예 입니다.

나는 그 대답이 좋다고 생각했다. 사실, 그것은 제가 찾고 있던 것을주었습니다. :nth-of-type그것은 제 상황에서 효과가있었습니다. (그래서 감사합니다, @Bdwey.)

나는 처음에 @BoltClock (답이 본질적으로 잘못되었다는 말)의 주석을 읽고 내 사용 사례를 확인했기 때문에 그것을 무시했습니다. 그런 다음 @BoltClock이 300,000+ (!)의 명성을 얻었고 그가 CSS 전문가라고 주장하는 프로필을 가지고 있다는 것을 깨달았습니다. 흠, 좀 더 가까이보아야 할 것 같아요.

다음과 같이 밝혀졌습니다 : div.myclass:nth-of-type(2)"div.myclass의 두 번째 인스턴스"를 의미하지 않습니다. 오히려 "div의 두 번째 인스턴스이며 'myclass'클래스도 있어야합니다."를 의미합니다. 이는 인스턴스 div사이에 s 가있을 때 중요한 차이점 div.myclass입니다.

It took me some time to get my head around this. So, to help others figure it out more quickly, I've written an example which I believe demonstrates the concept more clearly than a written description: I've hijacked the h1, h2, h3 and h4 elements to essentially be divs. I've put an A class on some of them, grouped them in 3's, and then colored the 1st, 2nd and 3rd instances blue, orange and green using h?.A:nth-of-type(?). (But, if you're reading carefully, you should be asking "the 1st, 2nd and 3rd instances of what?"). I also interjected a dissimilar (i.e. different h level) or similar (i.e. same h level) un-classed element into some of the groups.

Note, in particular, the last grouping of 3. Here, an un-classed h3 element is inserted between the first and second h3.A elements. In this case, no 2nd color (i.e. orange) appears, and the 3rd color (i.e. green) shows up on the 2nd instance of h3.A. This shows that the n in h3.A:nth-of-type(n) is counting the h3s, not the h3.As.

Well, hope that helps. And thanks, @BoltClock.

div {
  margin-bottom: 2em;
  border: red solid 1px;
  background-color: lightyellow;
}

h1,
h2,
h3,
h4 {
  font-size: 12pt;
  margin: 5px;
}

h1.A:nth-of-type(1),
h2.A:nth-of-type(1),
h3.A:nth-of-type(1) {
  background-color: cyan;
}

h1.A:nth-of-type(2),
h2.A:nth-of-type(2),
h3.A:nth-of-type(2) {
  background-color: orange;
}

h1.A:nth-of-type(3),
h2.A:nth-of-type(3),
h3.A:nth-of-type(3) {
  background-color: lightgreen;
}
<div>
  <h1 class="A">h1.A #1</h1>
  <h1 class="A">h1.A #2</h1>
  <h1 class="A">h1.A #3</h1>
</div>

<div>
  <h2 class="A">h2.A #1</h2>
  <h4>this intervening element is a different type, i.e. h4 not h2</h4>
  <h2 class="A">h2.A #2</h2>
  <h2 class="A">h2.A #3</h2>
</div>

<div>
  <h3 class="A">h3.A #1</h3>
  <h3>this intervening element is the same type, i.e. h3, but has no class</h3>
  <h3 class="A">h3.A #2</h3>
  <h3 class="A">h3.A #3</h3>
</div>


Perhaps using the "~" selector of CSS?

.myclass {
    background: red;
}

.myclass~.myclass {
    background: yellow;
}

.myclass~.myclass~.myclass {
    background: green;
}

See my example on jsfiddle

참고URL : https://stackoverflow.com/questions/2751127/how-to-select-the-first-second-or-third-element-with-a-given-class-name

반응형