The JS and HTML at this jsfiddle and shown below is part of a settings menu, which is a list of URLs and an 'x' button next to each. This is part of my fork of this RSS app, so not something I'm building from scratch. In practice it looks like:
x foo.com
x bar.com/rss
x baz.com/feed
The renderSettings() function injects data from a JSON array into the <template id="settings-feed-item"> div, which is why nothing shows up in the JSFiddle preview. That function also adds the onclick functionality to every instance of the #remove div.
Aside from other code I've trimmed out for brevity, I want to apply CSS styling to a #feedurl when the #remove next to it is clicked.
The problem I'm having is that I can't figure out how to select the #feedurl. I've tried this. and the closest() method but I can't select it. Everything I've tried so far gets me TypeError: undefined is not an object in the console. What am I missing?
<section id="feedsection">
<ul id="feeds">
<template id="settings-feed-item">
<li>
<a id="remove">x </a><span id="feedurl"></span><a></a>
</li>
</template>
</ul>
</section>
// RENDER SETTINGS MENU
function renderSettings() {
keywords.value = state.keywords;
newsFeeds.innerHTML = '';
state.feeds.forEach(f => {
const el = document.importNode(feedItem.content, true).querySelector('li');
el.querySelector('span').innerText = simplifyLink(f.url);
// ...
// onclick `#remove`
el.querySelectorAll('a')[0].onclick = () => {
// SELECT URL NEXT TO CLICKED X
};
// ...
});
}
You want the next sibling.
el.querySelectorAll('a')[0].onclick = (e) => {
e.currentTarget.nextElementSibling.classList.add('someclass');
};
BTW, IDs are supposed to be unique, so you shouldn't duplicate id="feedurl" in copy. Use classes instead of IDs.