Skip to content Skip to sidebar Skip to footer

Add Class To Dynamically Created Html Node

I thought this was going to be a bit easier to do, but I have spent a good 2 hours on it, without being able to figure it out. I have this output: and I am dynamically creating ab

Solution 1:

To target the last span and add the class with javascript, you'd use a selector, like span:last-child, that gets the last span inside output, and then you'd use classList.add(). There is no addClass(), that's a jQuery method.

output.querySelector('span:last-child').classList.add('total')

FIDDLE

Solution 2:

Not a fix for the problem, but this removes the problem: You can do this in pure CSS, using the last-of-type selector. This is the best solution IMHO. https://developer.mozilla.org/nl/docs/Web/CSS/:last-of-typehttps://developer.mozilla.org/en-US/docs/Web/CSS/%3Alast-child

Codepen example: http://codepen.io/anon/pen/gMOXqK Since this doesn't even need JavaScript, and only uses CSS without complicated selectors, this seems like the best solution.

Possible fixes for your problem: Your addClassList syntax is incorrect. See: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

output.classList.add("total"); 

This is the correct addClass syntax.

Is there any reason why you would add the class with JavaScript, instead of adding it instantly? If you would pass an (optional) class parameter, you could pass the class when adding the totals (assuming you know when you're adding the totals).

functionoutputValue(value){
    outputValue(value,"");
}

functionoutputValue(value, class){
    output.innerHTML += "<br>" + "<span class='" + class + "'>" + value + "</span>";
}

Post a Comment for "Add Class To Dynamically Created Html Node"