简体   繁体   中英

How to apply css to a specific item id within a container with specific Id using Jquery?

I have three containers with different Ids but similar content with similar ids, one is books, the others pens and pencils.

How do i apply a style to an item when it is clicked under each of these containers with their ids?

<div id="Books">
<div id="1">Stack</div>
<div id="2">Flow</div>
</div>

<div id="Pens">
<div id="1">big</div>
<div id="2">small</div>
</div>

<div id="Pencils">
<div id="1">big</div>
<div id="2">small</div>
</div>

Follows a full working solution using vanilla javascript :

 function clicked(element) { element.classList.add('success') }
 .success { color: green; }
 <div id="Books"> <div id="1" onclick="clicked(this)">Stack</div> <div id="2" onclick="clicked(this)">Flow</div> </div> <div id="Pens"> <div id="1" onclick="clicked(this)">big</div> <div id="2" onclick="clicked(this)">small</div> </div> <div id="Pencils"> <div id="1" onclick="clicked(this)">big</div> <div id="2" onclick="clicked(this)">small</div> </div>

You should disambiguate your IDs to be unique within a document, which would neatly eliminate your problem. If you need to address multiple elements that share a given role, CSS classes are the way to go.

As stated in the comment section by @collapsar

Find the below answer with jquery

$('#Books').click(()=>{
 $(this).find('#1').css('background-color', 'red');
 $(this).find('#2').css('background-color', 'blue');
})

$('#Pens').click(()=>{
 $(this).find('#1').css('background-color', 'red');
 $(this).find('#2').css('background-color', 'blue');
})

$('#Pencils').click(()=>{
 $(this).find('#1').css('background-color', 'red');
 $(this).find('#2').css('background-color', 'blue');
})

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