I'm trying to highlight only the number between the brackets in regular js. Colors are based on value (type of fruit in this scenario). HTML
<a class="temple" href="something @ URL">LARGE FRUIT (215)</a>
<a class="temple" href="something @ URL">PINEAPPLE (38)</a>
<a class="temple" href="something @ URL">RED APPLE (76)</a>
My Dict
var my_dict = {'BLUE':['ORANGE'], ['GRAPE']
'YELLOW':['PINEAPPLE'], ['KIWI']}
I could do them independently using but it's messy and may break the code if a tag is removed:
let Pineapple = document.querySelector('.temple')
PINEAPPLE.innerHTML = PINEAPPLE.innerHTML.replace(/\([^\)]*\)/, '<span class="red">$&</span>')
This is what I have so far:
function color(){
let fruits = document.querySelector('.temple')
for (let i = 0; i<fruits.length; i++) {
let str = fruits.innerHTML //this gives me the text I need.
My goal is to use the results (value) to find the key and ultimately color just the number.
that ?
const my_dict =
{ BLUE: [ 'ORANGE', 'GRAPE' ]
, YELLOW: [ 'PINEAPPLE', 'KIWI' ]
, RED: [ 'APPLE' ]
};
// ES5 code
const my_dict_reverse =
Object
.keys( my_dict)
.reduce( function(r,k)
{
my_dict[k].forEach( function(fruit) { r[fruit] = k } );
return r;
},{});
// my_dict_reverse = { ORANGE: 'BLUE', GRAPE: 'BLUE', PINEAPPLE: 'YELLOW', KIWI: 'YELLOW', APPLE: 'RED' }
document
.querySelectorAll('.temple')
.forEach( function(el)
{
let pos = el.textContent.search(/\([^\)]*\)/)
, fruit = el.textContent.slice(0,pos)
, val = el.textContent.slice(pos)
, colorClass = my_dict_reverse[ fruit.replace(/^\s+|\s+$/g,'')] || ''
;
el.innerHTML = fruit
+ '<span class="' + colorClass + '">'
+ val +'</span>';
});
/* ES10 code ...
const my_dict_reverse = Object.keys( my_dict).reduce((r,k)=>
{
my_dict[k].forEach(fruit=>r[fruit]=k)
return r
},{})
document.querySelectorAll('.temple').forEach(el=>
{
let [fruit, val] = el.textContent.split(/(?=\()|(?<=\))/)
, colorClass = my_dict_reverse[ fruit.trim()] ?? ''
;
el.innerHTML = `${fruit}<span class="${colorClass}">${val}</span>`
})
*/
body { background: steelblue; }
a.temple {
color : black;
float : left;
clear : both;
text-decoration : none;
}
span.RED { color : red; }
span.BLUE { color : blue; }
span.YELLOW { color : yellow; }
<a class="temple" href="something @ URL">LARGE FRUIT (215)</a>
<a class="temple" href="something @ URL">PINEAPPLE (38)</a>
<a class="temple" href="something @ URL">APPLE (76)</a>