Create DOM with jquery and check existence

0

I have created a function that performs an ajax query with data return in json, when this function receives the data, it checks if the DOM exists, if it does not exist, it creates it.

The question is: When the DOM exists instead of creating it, you must change the data within that DOM.

Example:

function getInfo(clas, div, ty) {
    $.get('MI ARCHIVO PHP?t=' + ty, function(data){
        if($(div).length == 0) {
            clas.append('<div class="' + div + '">' + data.text + '</div>');
        }else{
            $(div).html(data.text);
        }
    }, 'json');
}

The thing is that, the first time it works perfectly, I create the div with the correct information, but the second when I call the function with a setInterval instead of changing the information inside the div, what it does is repertirme it constantly, I mean , that on the screen I end up with a lot of div with the same class.

The variables of the function are: getInfo ($ ('. infobox'), '.info', 0); The first refers to a div that already comes within the html file, the second is the class of the div that you have to create or modify and the third part of the php file in the ajax. I must say that the "infobox" contains several information boxes, and always repeats them to me.

What am I doing wrong?

Thanks in advance.

    
asked by El Tito Barte 10.06.2017 в 13:11
source

1 answer

1

Going around, I managed to find out what the problem was. Resuta that in the second variable of the function, the class '.info' put it with the '.' when it should be without the point.

The original variables were getInfo ($ ('. infobox'), '.info', 0) when it should be getInfo ($ ('. infobox'), 'info', 0).

The reason for this is because in the function at the time of adding the DOM to the variable clas 'clas.append (' ')' that variable 'div' had the '.', so javascript did not recognize it . The solution was to remove the point and add it to the function when searching for the DOM.

$ ('.' + div) .length == 0 here and if I found it perfectly.

    
answered by 10.06.2017 в 13:43