I'm trying to set up a function on my page that will iterate through a series of news titles and will strikethrough the title if it contains a specific marker.
The titles are pulled from a WordPress post database and displayed within a <div>
with ID="news"
. Each specific title is a link <a>
with class="title"
.
I am first collecting all the titles into an array so I can iterate through them but for some reason, it doesn't work properly.
My code is:
<script type="text/javascript">
//first I create the array
var test_DOM = document.getElementById("news").getElementsByClassName("title");
//then I set the marker
var marker = "[X]"
//then I wirte the function to iterate through the array://
function checkX() {
for(i in test_DOM){
if (i.includes(marker)) {
i = "<del>", i, "</del>";
console.log(test_DOM[i], "changed")
}
console.log(test_DOM[i].innerHTML)
}
};
//and I call the function
checkX()
An expected result would be to see the list of news to change from
[x] News 1
[EG] News 2
to
[x] News 1 <- struck through
[EG] News 2 <- still the same
However, nothing happens. I know that getElementsByClassName gets me an array of objects and that I should use .innerHTML and some point, but using it inside the function like
function checkX() {
for(i in test_DOM){
if (i.innerHTML.includes(marker)) {
i.innerHTML = "<del>", i, "</del>";
console.log(test_DOM[i], "changed")
}
console.log(test_DOM[i].innerHTML)
}
};
gives an error of "TypeError: i.innerHTML is undefined"
", i, "";` does not combine the strings, it uses the [comma operator](https://stackoverflow.com/questions/3561043/what-does-a-comma-do-in-javascript-expressions) and returns only the last item. Also `i` would not be each *value* of `test_DOM` but each *key* from `test_DOM`. – VLAZ May 15 '19 at 08:28