I have a function called adName that I am trying to make prepend a span tag with text inside the code element with a class obj. The problem is that I keep getting errors, and the span tag isn't inside the code tag, instead it is right beside it. Also, I'm trying to make all the code tags that have class of obj have span tags. But in my code, the last class has the span tag of 'Object':
So there are 3 objects <code class="obj">poke1</code>, <code class="obj">poke2</code> and pokeAb, and there is a constructor called Pokemon. Poke1&2 has properties of name, type, and attack. When I activate the call method with pokeAb's method called fight, and I put one of the poke's (1 or 2) inside the parenthesis, it will grab the properties of the object and print out something depending on what poke I called.
function adName(clas, name, color, back) {
var a = document.getElementsByClassName(clas);
var b = document.createTextNode(name);
var c = document.createElement('span').appendChild(b);
var d = document.querySelectorAll('code');
for (var i = 0; i < a.length; ++i) {
a[i].parentNode.insertBefore(c, a[i]);
a[i].style.background = back;
a[i].style.color = color;
}
}
adName('obj','Object:','#003366','#99ccff');
When you use a[i].parentNode, you are reaching the p element and adding the span to a place before code element. You should do like this:
function adName(clas, name, color, back) {
var a = document.getElementsByClassName(clas);
var b = document.createTextNode(name);
var c = document.createElement('span');
c.appendChild(b);
var d = document.querySelectorAll('code');
for (var i = 0; i < a.length; ++i) {
a[i].innerHTML = c.outerHTML + a[i].innerHTML;
a[i].style.background = back;
a[i].style.color = color;
}
}
adName('obj','Object:','#003366','#99ccff');
JSFiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With