I am trying to add an active class to a div by means of a data id. Currently clicking on it does nothing and I get no errors in console. The data is generated with jQuery ie: dynamic data so not sure if that has something to do with it. So, when the page loads, data is fetched from an api and the html output is rendered with javascript. There are multiple card divs inside the columns div, they just have different data id's.
$('.columns').append(cardData);
$(".columns .card[data-id='" id "']").addClass('active');
CodePudding user response:
You obviously need to wait until the HTML has been requested and added to the page.
You need to access the cards by data-id within the element containing the
columns
class.
This example uses find
to locate the card with the specified id within the .columns
element.
// Mock API request to deliver HTML
function mockApi() {
return new Promise(res => {
setTimeout(() => {
res(`
<div data-id="1">1</div>
<div data-id="2">2</div>
<div data-id="3">3</div>
<div data-id="4">4</div>
`);
}, 1000);
});
}
// Cache the columns element
const columns = $('.columns');
// Append HTML to the columns element
function appendHtml(html) {
columns.append(html);
}
// Accept an id, use that within a selector
// and then use that with `find` to select the
// appropriate card, and update its class.
function updateCard({ id }) {
const selector = `.card[data-id='${id}']`;
const el = columns.find(selector);
el.addClass('active');
}
// Get the data, update the DOM, and
// then update the card
async function main() {
const html = await mockApi();
appendHtml(html);
updateCard({ id: 2 });
}
main();
.active { background-color: #efefef; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div ></div>