Reputation: 37
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 :
karate
inside the list, then go back to the closest <li>
<li>
tag) as the start position. </li>
tag.style="color:red;"
to the <li>
tag.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
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