Jacob Seen Jacob Seen - 1 year ago 103
Javascript Question

JavaScript - Adding span to children?

So I got an code which should add span if it doesn't exist on children, but at the moment it adds it to only one, but not on others because "code" sees it already exists. How to do it, that if there will be new div, then it adds to that as well?

if($("#itemcart div").children().length > 0){

} else{
$("#itemcart div").append($("<span> X</span>"));

Answer Source

Don't know if i understood, anyway, assuming you have multiple div and you want to check if EVERY div has a child span you can do something like this:

$("#itemcart div").each(function(){
    if( $(this).children().length > 0){

    } else{
        $(this).append($("<span> X</span>"));

This will iterate through every div. In this loop, you can use this to refers to the current div and check if he has or not a children span

See the example here: https://jsfiddle.net/3qkpLnd9/1/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download