Hassang
Hassang

Reputation: 37

How to extract html from certain position to another and add an attribute to it using JavaScript?

I have this html :

<ul>
   <li><a href="img/karate/image1.jpg">Image 1</a></li>
   <li><a href="img/karate/image2.jpg">Image 2</a></li>
   <li><a href="img/boxing/image3.jpg">Image 3</a></li>
   <li><a href="img/karate/image4.jpg">Image 4</a></li>
   <li><a href="img/kungfu/image5.jpg">Image 5</a></li>
</ul>  

<button type="button">Red Color</button>

I want to :

  1. Locate the word karate inside the list, then go back to the closest <li>
  2. Mark it (the <li> tag) as the start position.
  3. The end position would be its closing </li> tag.
  4. Store the result in a string variable.
  5. Add/append this attribute : style="color:red;" to the <li> tag.
  6. All this by hitting the button, and using JavaScript.

The result : Image 1, Image 2 and Image 4 will be colored Red, Image 3 and Image 5 will be ignored.

I don't want to use JQuery or imported JS file like Cherrio because I want to understand every line !

I found things called web scraping, robots crawling... but i still can't understand it so any help would be much much appreciated.

Thank you very much.

Upvotes: 1

Views: 88

Answers (1)

zhuravlyov
zhuravlyov

Reputation: 503

"use strict";

let button = document.querySelector('#button');
button.addEventListener('click', onButtonClick);

function onButtonClick() {
    let urls = document.querySelectorAll('a');

    for (let i = 0, max = urls.length; i < max; i++) {

        if (urls[i].href.indexOf('karate') !== -1) {
        
            if(urls[i].parentNode.tagName === 'LI') {
                urls[i].parentNode.className = 'makeRed';
            }
            
        }
    }
}
.makeRed, .makeRed a {
  color: #FF0000;
}
<ul>
    <li><a href="img/karate/image1.jpg">Image 1</a></li>
    <li><a href="img/karate/image2.jpg">Image 2</a></li>
    <li><a href="img/boxing/image3.jpg">Image 3</a></li>
    <li><a href="img/karate/image4.jpg">Image 4</a></li>
    <li><a href="img/kungfu/image5.jpg">Image 5</a></li>
</ul>

<button type="button" id="button">Red Color</button>

Upvotes: 2

Related Questions