How do I access the HTML attributes within this string?
'This champion has <ability value=43>Immunity: Disease</ability>. While you control at least 5 Zombies, this unit gains <ability value=2147>Swarm: Festering Corpse</ability>.'
I want to get the data from the value attribute within the ability tags. Is this possible with Javascript
CodePudding user response:
You can simulate the text as HTML using document.createElement
:
var text = "This champion has <ability value=43>Immunity: Disease</ability>. While you control at least 5 Zombies, this unit gains <ability value=2147>Swarm: Festering Corpse</ability>.";
var newNode = document.createElement("span");
newNode.innerHTML = text;
var elems = newNode.children;
var i = 0;
while(i < elems.length) {
console.log(elems[i].innerText, elems[i].getAttribute("value"));
i ;
};
CodePudding user response:
You can achieve your result by converting your string to html and then read abilities from produced html, like this:
const str = 'This champion has <ability value=43>Immunity: Disease</ability>. While you control at least 5 Zombies, this unit gains <ability value=2147>Swarm: Festering Corpse</ability>.'
const abilities = [];
const tempEl = document.createElement('div');
tempEl.innerHTML = str;
const abilityTags = tempEl.querySelectorAll('ability');
abilityTags.forEach((ability) => {
abilities.push(ability.getAttribute('value') /*or whatever you want read from ability tag*/ )
});
console.log(abilities)