I have the following DOM structures given below and I would like to get to the hyperlink buttons (a) in both the scenarios. I have made both the header's (header1 and recordHeader1) clickable (cursor:pointer). So if I click on say anywhere (say if I click on the headerTitle) in header1 or (name, job_title) in recordHeader1, I would like to find the hyperlink button and perform certain click functionality. There might be more of those scenario but in all the scenario's, there is a parent header like the one's given below and the parent header always has the hyperlink element somewhere in the DOM. Please let me know what I'm doing wrong here.
Scenario 1:
<div class="header1">
<a href="#" class="downArrow k-icon k-minus"></a> <!-- This element -->
<img class="foundIcon" src="https://google.com">
<div class="headerTitle">Contacts</div>
</div>
Scenario 2:
<div class="recordNew">
<div class="recordHeader1">
<ul>
<li>
<div class="arrowContainer">
<a href="#" class="downArrow k-icon k-minus"></a> <!-- This element -->
</div>
</li>
<li>
<div class="nameContainer">
<span class="name">John Doe </span>
</div>
</li>
</ul>
</div>
<span class="job-title">Marketing Professional </span>
</div>
</div>
What I have tried?
// This is a generic function that makes the header clickable based on any element click
function makeRowClickable() {
$(".headerTitle, .name, .job_title, .foundIcon").on("click", function(e) {
// doesn't seem to work and find the correct element
console.log($(e.target).closest(".header1").find(".downArrow"));
});
}
Try this
const headerClick = (e, header, downArrow) => {
// programatically click on the anchor tag
downArrow.click();
}
// get all .header1 elements
[...document.querySelectorAll('.header1')]
// add all .recordHeader1 elements to the array
.concat([...document.querySelectorAll('.recordHeader1')])
// add event listener on each .header1 and .recordHeader1
.forEach((header) => header.addEventListener('click', (e) => {
// inside the click handler send the event, the header element, and its child downarrow element
headerClick(e, header, header.querySelector('.downArrow'))
}));