简体   繁体   中英

How to add class to an element if a different element on the page has a certain class

jsfiddle.net/8KgRd

I'm trying to select the first header in my main container and add a class to it. But I want this to be dependent on what section of the website they are on.

For example. If they are on the "EAST Core" page, I want the header to be orange.

The HTML is populated by the backend so I can't hardcode the classes in.

HTML

<ul id="mainNav" class="nav navbar-nav">
    <li class='linked'><a href="/?id=12">EAST Program</a>
    </li>
    <li class='active linked'><a href="/?id=86">EAST Core</a>
    </li>
    <li class='linked'><a href="/?id=20">Get More Involved</a>
    </li>
    <li class=''><a href="/?id=21">Sponsors & Exhibitors</a>
    </li>
    <li class=''><a href="/?id=22">Newsroom</a>
    </li>
</ul>

<div id="mainbar">
     <h1>This is the title I want to add a class to.</h1>
</div>

.

JAVASCRIPT

if ($("#mainNav li:nth-child(2)"): hasClass("active")) {
$("#mainbar h1:first-child").addClass("orangeHead");
};

UPDATE: Solved by:

if ( $("#mainNav li:nth-child(2)").hasClass("active") ) {
    $("#mainbar h1:first-child").addClass("orangeHead");
}

One way would be:

$("#mainNav li:nth-child(2).active")
    .closest("#mainNav").next()
    .find("h1:first-child").addClass("orangeHead");

Another way (your original way with syntax error fixed):

// this is probably the "better" way to do it of the two
if ( $("#mainNav li:nth-child(2)").hasClass("active") ) {
    $("#mainbar h1:first-child").addClass("orangeHead");
}

You can get the index of the active navigation element, and then update the other element based on this information, eg:

var colorClasses = ['redHead', 'orangeHead', 'blueHead', 'greyHead', 'purpleHead'],
    index         = $("#mainNav").children(".active").index();

$("#mainbar").addClass(colorClasses[index]);

This is a bit more modular than your code and will be easier to maintain (no need to have different code on different pages, this will work on all pages). Basically the index of the active element just needs to line-up with the index of the colors array for the class that gets added to the #mainbar element.

您可以根据自己的活动状态切换标题的类

$("#mainbar h1:first-child").toggleClass("orangeHead", $("#mainNav li:nth-child(2)").hasClass("active"));

it's interesting how you can have different ways to achieve the same result. Here is another option

toOrange = $("#mainNav").find("li").eq(1);
if( toOrange.is(".active") ){
   $("#mainbar > h1").addClass("orangeHead");
}

See JSFIDDLE

I personally give preference to the .eq() method over pseudo classes, which is (arguably) faster in many cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM