HWR
HWR

Reputation: 31

A function that will loop through span class and add text at the end

I'm trying to do a function, used some pieces of other functions, to loop through the class with a specific name using JS and adding a '*' at the end of whatever is inside those HTML tags. It's not working perfectly, so what do I need to change? The class name is "price".

function insertAfter(referenceNode, newNode) {
    referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}

function getValues(objName) {
    var arr = new Array();
    var el = document.createElement("span");
    el.innerHTML = "*";
    arr = document.getElementsByClassName(objName);
    for(var i = 0; i < arr.length; i++) {
        var obj = document.getElementsByClassName(objName).item(i);
        insertAfter(obj, el)
    }
};

getValues("price");

Upvotes: 0

Views: 1263

Answers (2)

hereandnow78
hereandnow78

Reputation: 14434

what do you mean by "it is not working"?

document.getElementsByClassName already returns an array, you dont need to fetch it twice, do it like that:

arr = document.getElementsByClassName(objName);
for(var i = 0; i < arr.length; i++) {
    var obj = arr[i];
    insertAfter(obj, el);
}

rewrite your insertAfter to really do an insertAfter:

function insertAfter(referenceNode, newNode) {
    referenceNode.insertAfter(newNode, referenceNode.lastChild);
}

see a working example here: http://jsfiddle.net/BJ3YR/

Upvotes: 0

yogi
yogi

Reputation: 19601

Do this

function getValues(objName) {
            var arr = new Array();
            arr = document.getElementsByClassName(objName);
            for (var i = 0; i < arr.length; i++) {
                var el = document.createElement("span");
                el.innerHTML = "*";
                var obj = document.getElementsByClassName(objName).item(i);
                insertAfter(obj, el)
            }
        };

actually you need to create a new el every time you want to insert that element into the tag, Else you will ending up adding only single * element at the end of the last tag in the DOM having "price" class.

Upvotes: 1

Related Questions