简体   繁体   中英

How to change the color of visited anchor link in java script dom

I have a problem in Dom. I want to change the color of a visited link on the basis of alreadyRead (a Boolean). I am new in this field so if I am doing any wrong please forgive me for that. Here is my code snippet. Thanks in advance!

var books = [
  {
    title: 'The Design of EveryDay Things',
    author: 'Don Norman',
    alreadyRead: false
  },
  {
    title: 'The Most Human Human',
    author: 'Brian Christian',
    alreadyRead: true
  }
];

var appHandle = document.getElementById('app');
var ulTag = document.createElement('ul')
books.forEach(book =>{
  if(book.alreadyRead === true){
    document.linkcolor="green"
  } else{
    document.linkcolor ="red"
  }
  var liTag = document.createElement('li');
  var navList =document.createTextNode(`${book.title} by ${ book.author}`)
  var aTag = document.createElement('a')
  aTag.setAttribute('href','#');
  aTag.appendChild(navList)
  liTag.appendChild(aTag);
  ulTag.appendChild(liTag);
})
appHandle.appendChild(ulTag)

At its simplest, you could achieve what you seem to want with the following line:

aTag.classList.toggle('alreadyRead', book.alreadyRead);

This line uses the Element.classList API to toggle the alreadyRead class-name on the relevant aTag element node, based on the switch that follows the class-name. If the switch returns true the class is added (if not already present) or if the switch returns false the class-name is removed (if present).

 var books = [{ title: 'The Design of EveryDay Things', author: 'Don Norman', alreadyRead: false }, { title: 'The Most Human Human', author: 'Brian Christian', alreadyRead: true } ]; var appHandle = document.getElementById('app'); var ulTag = document.createElement('ul') books.forEach(book => { var liTag = document.createElement('li'); var navList = document.createTextNode(`${book.title} by ${ book.author}`); var aTag = document.createElement('a') aTag.setAttribute('href', '#'); aTag.appendChild(navList) liTag.appendChild(aTag); ulTag.appendChild(liTag); aTag.classList.toggle('alreadyRead', book.alreadyRead); }) appHandle.appendChild(ulTag) 
 .alreadyRead { color: limegreen; } 
 <div id="app"></div> 

JS Fiddle demo .

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM