How to change link color by using javascript without id and class

I want to change the BOOK link to red color. how can I change it by javascript without adding any other id and class? I tried to using sections but not work. 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>

Answer

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>.

Leave a Reply

Your email address will not be published. Required fields are marked *