JoeBe
JoeBe

Reputation: 1290

How to select this element and children of next element in one line?

I want to change CSS settings on click for a headline p and other p's located in a div next to the headline p

The HTML structure

<div class="outerDiv">
    <p id="headline">My headline</p>
    <div id="listContainer">
        <p>Text 1</p>
        <p>Text 2</p>
        <p>Text 3</p>
        <p>Text 4</p>
    </div>
</div>

Current Solution

Currently, I use jQuery's next(), children() and addBack() approach, but it only selects the children and is not merging it back with the headline p (I assume because addBack() is going back to the second last child of children (?))

$("p#headline").click(function() {
    $(this).next().children().addBack().css({"background-color": "#000", "color": "#fff"})
})

How can I achieve a selection of both the children and the headline p without writing a second line? (jQuery or javascript)

EDIT

Some of the CSS settings are based on variables' values which may change

Upvotes: 0

Views: 210

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075785

How can I achieve a selection of both the children and the headline p without writing a second line?

You can do this:

$(this).next().children().add(this).css(/*...*/);

addBack didn't work because it added back the next element, not this.


But I wouldn't do that. Instead, I'd do this:

$(this).closest(".outerDiv").addClass("some-class-named-semantically");

...and have a CSS rule like:

.some-class-named-semantically #headline,
.some-class-named-semantically #listContainer p {
    background-color: #000;
    color: #fff;
}

I don't know what clicking this headline means, but for instance if it selects it, then the class name might be selected.

Re your edit:

Some of the CSS settings are based on variables' values which may change

Usually that can be addressed with theming classes. But in any case, the main question you asked is answered at the beginning of this answer.

Upvotes: 2

Related Questions