Claire
Claire

Reputation: 113

How to change link color by using only JavaScript not CSS or HTML

I want to change the BOOK link to red color. how can I change it by JavaScript without adding an id or class? I tried using sections but it's not working. Thanks.

var sections = document.getElementsByClassName('section');
sections.getElementsByTagName("a")[2].style.color="red";
sections.getElementsByTagName("li")[2].style.color="red";
<section>
    <ul>
        <li><a href="">1</a></li>
    </ul>
 </section>
 <section>
    <ul>
        <li><a href="">2</a></li>
    </ul>
 </section>
 <section>
    <ul>
        <li><a href="">3</a></li>
    </ul>
 </section>

<section>
    <div class="Search-view">
        <ul>
            <li><a href="">Search</a></li>
            <li><a href="">View </a></li>
            <!-- change book to red -->
            <li><a href="">Book</a></li> 
            <li><a href="">Sell</a></li>
            <li><a href="">Get</a></li> 
        </ul>
    </div>
</section>

Upvotes: 1

Views: 81

Answers (3)

Miu
Miu

Reputation: 844

Issue

.getElementsByClassName('section') is used although there is no tag with class .section. It gets nothing.

Solution

// Get all a tags
const allA = document.querySelectorAll('a');

allA.forEach(a => {
  // If text in a tag is 'book'
  if (/^book$/i.test(a.textContent)) {
    // Change color to red
    a.style.color = 'red';
  }
})
<section>
  <ul>
    <li><a href="">1</a></li>
  </ul>
</section>
<section>
  <ul>
    <li><a href="">2</a></li>
  </ul>
</section>
<section>
  <ul>
    <li><a href="">3</a></li>
  </ul>
</section>

<section>
  <div class="Search-view">
    <ul>
      <li><a href="">Search</a></li>
      <li><a href="">View </a></li>
      <!-- change book to red -->
      <li><a href="">Book</a></li>
      <li><a href="">Sell</a></li>
      <li><a href="">Get</a></li>
    </ul>
  </div>
</section>

Personally, I recommend adding an ID to the a tag of 'book' like <a id="book">Book</a>.

Upvotes: 2

zergski
zergski

Reputation: 833

There are better ways of doing this.. like through css and its :nth-child() pseudo selector. But with your code just do this:

var sections = document.getElementsByTagName('section');
sections[sections.length-1].getElementsByTagName("li")[2].getElementsByTagName("a")[0].style.color="red"; 

With only CSS just add this ruleset to your stylesheet

.Search-view li:nth-child(3) a {
   color: red;
}

But ids and classes are you friends. Use them.

Upvotes: 1

Aiman_Irfan
Aiman_Irfan

Reputation: 375

I guess you define section as a class and then you try to override it with Tag. Because it said the error is on the second line, so I guess the override fail. Try to remove the class and use the Tag on the section variable

Upvotes: 1

Related Questions