skip to Main Content

I have a html look like this

<div id="mainDiv">
    <p></p> //this can be any tag like <ul></ul> or <h1></h1>...
    <ul></ul> //this can be any tag like <p></p> or <h1></h1>...
    <div></div> //this too
</div>

I want to apply display:none to the second element in #mainDiv (in this case it’s <ul></ul> ) so that it would be hidden.

How could I achieve it?

4

Answers


  1. Use nth child selector with universal selector *

    #mainDiv * {
      border: 2px solid green;
    }
    
    #mainDiv *:nth-child(2) {
      border: 2px solid red;
    }
    <div id="mainDiv">
        <p></p> //this can be any tag like <ul></ul> or <h1></h1>...
        <ul></ul> //this can be any tag like <p></p> or <h1></h1>...
        <div></div> //this too
    </div>
    Login or Signup to reply.
  2. You need the :nth-child selector

    #mainDiv :nth-child(2) {
      display: none
    }
    <div id="mainDiv">
      <p>First is a Paragraph </p>
      <ul>
        <li>Second element is an UL</li>
      </ul>
      <div>Third is a div</div>
    </div>
    Login or Signup to reply.
  3. I believe this will help you.

    <div id="mainDiv">
        <p>This is the first line </p> 
        <ul hidden> This line will be hidden</ul>
        <div></div>
    </div>
    
    Login or Signup to reply.
  4. I suggest you to use:

        #mainDiv *:nth-child(2){
                    display: none;
            }
    

    The :nth-child(n) selector matches every element that is the nth child, regardless of type, of its parent, while * is a selector who selects all elements but also select all elements inside another element.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search