Right way to get a certain div

Asked

Viewed 66 times

1

I’m trying to figure out a way to access a div via jquery to manipulate it. Follow the code:

<div> <!-- Essa é a div que quero acessar -->
  <div>
    <div>
      <div id="conteudo">...</div>
    </div>
  </div>
</div> 

As shown in the comment above, the div I want to access is the highest root of those shown here. I know these Ivs around are unnecessary, but sometimes some frameworks and cms put them, and then I find myself in a situation like this, having to access the div I want to move, as is in the comment.

What I do in jquery to access is the following:

$("#conteudo").parent().parent().parent().css('padding','15px');

How can I access this div without all this code? I often can’t get these unnecessary Ivs out, so I wanted to access the Ivs I want more effectively (imagine if there were 10 Ivs there, how many parents I would have to write...)

  • you can get the father of the div you want to manipulate?

  • yes, as I showed through Parent I do this, but wanted to do it in a better way, because if the div is involved by many other Divs, I will have to use several parents

  • You don’t understand the question, VC can know which is the father, or what kind of div exists above the one you want to manipulate?

  • ah yes. Look in some cases yes, but most of the time I can not. This is a case that I can not.

  • the problem then is just avoid calling .parent() several times?

  • Yeah, I wanted to see if you had something better to do in jquery.

Show 1 more comment

2 answers

4


Combine the function .parents() with the selector :eq():

$("#conteudo").parents(':eq(2)')

Note that indexing is at 0, so to access the 3rd level should be used 2.

  • Exactly that! I didn’t know this combination could be made!

1

Puts an identifier on it an ID or a class and calls it directly

<div id="esse"> <!-- Essa é a div que quero acessar -->
  <div>
    <div>
      <div id="conteudo">...</div>
    </div>
  </div>
</div> 

Then do the $('#esse').css('padding','15px'); if it is not possible to touch this div then the Penalty has already demonstrated the other way.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.