Working Dynamic Selectors (or Multiple Selectors) in Jquery

4

I have a Javascript (Jquery) code that takes characters from one DIV and throws this result to another DIV. For the DIV where I get the characters I created a function that adds a class dynamically, being p0, p1, p2, and so on. See:

$('.listagem .listagem-item .info-produto > a').each(function(i) {
            var $this = $(this); 
            var newClass = "nomep" + i++;
            $this.addClass(newClass);
        });

function firstnomep(){
        var str = $(".listagem .listagem-item .info-produto .nomep0").text();
        var res = str.slice(0,15);

        $('<div id="name-prod">'+res+'</div>').insertBefore(".listagem .listagem-item .info-produto .nomep0");}

I wanted to know how it is possible for me to create a function where this code works automatically for all DIVs, since the page can have more than 50 DIVs with the class "xpname". In the example above, it works correctly only for the DIV with class "namep0".

If I do not use the class "name xx" it picks up only the first selector it finds from ".liste.list-item .info-product" and inserts the same characters in all DIVs, which is not what desire.

    
asked by anonymous 18.06.2018 / 02:05

1 answer

1

Why do not you just do everything in each that you're adding to the CSS class?

var $this = $(this);
var str = $this.text();
var res = str.slice(0,15);

$('<div id="name-prod">'+res+'</div>').insertBefore($this); 

Instead of adding the CSS class

    
18.06.2018 / 02:23