4
\$\begingroup\$

Summary:

I need to hide several (pre-determined) divs based on a child element's ID.


Caviats:

I can't alter the HTML directly in any way (by modifying the literal .html file). The IDs of the child elements for which the parents are to be hidden are known and not likely to change often (or even at all).

I can't add CSS that will be available to the HTML page.


Here is the solution that I came up with

JavaScript

var toHide = $("#item2, #item3, #item6");
toHide.parent().hide();

HTML

<div id="container">
    <div>
        <div id="item1">
            <p>item 1</p>
        </div>
        <div>related item stuff</div>
    </div>
    <div>
        <div id="item2">
            <p>item 2</p>
        </div>
        <div>related item stuff</div>
    </div>
    <div>
        <div id="item3">
            <p>item 3</p>
        </div>
        <div>related item stuff</div>
    </div>
    <div>
        <div id="item4">
            <p>item 4</p>
        </div>
        <div>related item stuff</div>
    </div>
    <div>
        <div id="item5">
            <p>item 5</p>
        </div>
        <div>related item stuff</div>
    </div>
    <div>
        <div id="item6">
            <p>item 6</p>
        </div>
        <div>related item stuff</div>
    </div>
    <div>
        <div id="item7">
            <p>item 7</p>
        </div>
        <div>related item stuff</div>
    </div>
</div>

Is there a better way to select these multiple elements than by using $("#item2, #item3, #item6")?

Are there any options I'm missing?

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

That is pretty close to the optimal way of doing it.

Personally I would go for

//Hide items
$("#item2, #item3, #item6").parent().hide();
\$\endgroup\$
1
  • \$\begingroup\$ Thanks, @konijn. The only reason I separated my id selection from the .parent().hide() is because the actual ids are long and I wanted to preserve some readability. \$\endgroup\$
    – skeryl
    Commented May 8, 2014 at 21:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.