Reputation: 63
I'm building a glossary page. I have a list of each letter of the alphabet at the top of the page, linking via anchor text to the correct section of content. I want to remove the link from the letter if the letter has no terms.
I'm not getting any errors, but the code is not removing the link, or having any affect as far as I can tell.
Trying to remove link for B
function removeLink (){
var letternavcontent = document.getElementById("letternav").innerHTML;
var letter = document.getElementsByClassName("letter");
if ( letternavcontent.indexOf('B') > -1) {
letter.removeAttribute("href");
}
}
<p id="letternav">| <a class="letter"
href="/glossary.html#a">A</a> | <a class="letter"
href="/glossary.html#b">B</a></p>
Upvotes: 0
Views: 517
Reputation: 18473
How about this?
const removeLinkFromLetter = letter => {
// iterates over every letter element
[...document.querySelectorAll('.letter')].forEach(elt => {
// if the element has the specified letter as its text...
if (elt.innerText.trim()==letter) {
// ...change its content to the letter without the anchor tag
elt.innerHTML = letter;
}
});
}
window.onload = () => {
removeLinkFromLetter('A');
}
<p id="letternav">
|
<span class="letter">
<a href="/glossary.html#a">
A
</a>
</span>
|
<span class="letter">
<a href="/glossary.html#b">
B
</a>
</span>
|
</p>
Upvotes: 0
Reputation: 3777
Check this pen.
document.getElementsByClassName
returns all the elements with that class name, not just one. So you must loop through this list and check each one.
function removeLink (){
var letter = document.getElementsByClassName("letter");
for (var i = 0; i < letter.length; i++) {
if (letter[i].innerHTML.indexOf('B') > -1) {
letter[i].removeAttribute("href");
}
}
}
Upvotes: 1