Alex Ritter
Alex Ritter

Reputation: 1041

CSS Child Selectors - Need to target a child element

I'm fairly new to css selectors, but I have an html structure with child elements that I need to select. I've tried a few methods, but I am having a hard time selecting just the elements I need. To pre-answer: the HTML is added by a third party software, and I can not modify it in any way. This includes adding classes to elements.

Here is the HTML

<div class="smith-category-menu">
    <div>
        <div>
            <table></table>
            <div>
                <table></table>
            </div>
            <table></table>
            <div>
                <table></table>
            </div>
        </div>
    </div>
</div>

I need to be able to select the following:

<div class="smith-category-menu">
    <div>
        <div>
            <table SEELCT1></table>
            <div SELECT2>
                <table SELECT3></table>
            </div>
            <table SELECT4></table>
            <div SELECT5>
                <table SELECT6></table>
            </div>
        </div>
    </div>
</div>

I've tried div.smith-category-menu div div table and div.smith-category-menu div div table:first-child but they are both also selecting strange elements.

Any help would be greatly appreciated!

Upvotes: 2

Views: 2947

Answers (3)

Kai
Kai

Reputation: 3823

Using just a space in your selector, like

div table {
    ...
}

will select all table elements that are in a div's descendants, not just its direct descendant. Using a ">" instead will select direct descendants only.

div > table {
   ...
}

Upvotes: 0

Sourabh
Sourabh

Reputation: 8502

If that's the exact structure, you can use this selector:

div.smith-category-menu > div > div * {
    ...
}

or you can edit HTML a little:

<div class="smith-category-menu">
    <div>
        <div>
            <table class="old-classes select-me"></table>
            <div class="old-classes select-me">
                <table class="old-classes select-me"></table>
            </div>
            <table class="old-classes select-me"></table>
            <div class="old-classes select-me">
                <table class="old-classes select-me"></table>
            </div>
        </div>
    </div>
</div>

and use:

div.smith-category-menu .select-me {
    ...
}

Upvotes: 1

theftprevention
theftprevention

Reputation: 5213

You can use:

div.smith-category-menu>div>div * {
    border:1px solid #aa0000;
}

See this demo.

Upvotes: 5

Related Questions