I have been navigating through this HTML structure:
<ul>
<li class="item">
<span class="category">
most frequent text
</span>
</li>
<li class="item">
<span class="category">
some text
</span>
</li>
<li class="item">
<span class="category">
some text
</span>
</li>
<li class="item">
<span class="category">
most frequent text
</span>
</li>
<li class="item">
<span class="category">
most frequent text
</span>
</li>
</ul>
Using the following JavaScript code:
var myNodelist = Array.from(document.querySelectorAll(".category"));
var obj = {};
for(var i = 0; i < myNodelist.length; i++){
//convert array to object with unique elements and number of times
each element is repeated
var x = myNodelist[i].innerHTML;
//console.log(x);
if(!obj[x]){
obj[x] = 1;
} else {
obj[x]++;
}
}
var index = 0;
var max = 0;
for(var obIndex in obj) {
// Traverse the object to get the element
if(obj[obIndex] > max) {
max = obj[obIndex];
index = obIndex.replace(" ", "");
}
}
console.log(index + " is max time repeated: " + max + " times." );
var v = document.getElementsByClassName("category");
for(var m = 0; m < myNodelist.length; m++) {
var subText = myNodelist[m].childNodes;
var len = subText.length;
for (var jj = 0; jj < len; jj++) {
if(subText[jj].nodeType === Node.TEXT_NODE) {
console.log(subText[jj].nodeValue);
subText[jj].nodeValue =
subText[jj].nodeValue.replace(/Mock/,"123");
}
}
}
Currently, I am successfully retrieving the index along with the highest occurrence of a specific text in the HTML structure. After that, I iterate through the NodeList again, checking if it's a,
Node.TEXT_NODE
https://developer.mozilla.org/de/docs/Web/API/Node/nodeType
Right now, I can only replace the
textNode.value
with a different value. What I really want to achieve is to identify the parentNode of the textNode and apply a class to it if the condition for the index (highest occurrence) is satisfied. I came across
Adding a class to a given element. and ParentNode MDN
The issue I'm facing is determining how to access the parentNode outside the second loop and add a class to the parentNode so all parent elements (span tags) containing only the index (text value) receive a specific class.
Thank you for your assistance!