/    Sign up×
Community /Pin to ProfileBookmark

Dynamic Content and links

I have this JS code which works perfectly for content which is loaded dynamically and it the element I want is a single element.

However if it’s a hyperlink for example, or even a parent DIV how can I get this and not the IMG, SPAN or I tag?

[code]
<a href=”#” id=”homeLink”>
<img src=”…” alt=”…”>
<span>This is some text</span>
<i class=”font-awesome-font”>
</a>
[/code]

[code]
document.addEventListener(‘click’,function(e){
console.log(‘click’, e.target);

if(e.target && e.target.id == “homeLink”){
myFunction();
}
})
[/code]

I really don’t want plug in’s like jQuery etc

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@kiwisauthorNov 15.2021 — Currently I have a <a href-="#" onclick="myFunction(this)">...

with an if statement inside the JS.
Copy linkTweet thisAlerts:
@SempervivumNov 15.2021 — Two solutions come to my mind:

1st: Use the function `matches</C> in order to check if an element inside the a-tag has been clicked:
<CODE>
`<i>
</i> document.addEventListener('click', function (e) {
console.log('click', e.target);
// The function matches checks if the given selector
// matches the target.
// '#homeLink *' matches all elements inside the a-tag.
if (e.target &amp;&amp; e.target.matches('#homeLink *')) {
console.log('a-tag clicked');
// myFunction();
}
});<i>
</i>
`</CODE>
2nd: Check if the required a-tag is an ancestor of the target or element having been clicked:
<CODE>
`<i>
</i> document.addEventListener('click', function (e) {
console.log('click', e.target);
// The function closest tries to find a matching element
// upwards in the DOM
if (e.target &amp;&amp; e.target.closest('#homeLink')) {
console.log('a-tag clicked');
// myFunction();
}
});<i>
</i>
``
×

Success!

Help @kiwis spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.20,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...