4
I have a Javascript code (Jquery) that takes characters from a DIV and plays this result for another DIV. For the DIV where I take the characters I created a function that adds a class dynamically, being pName, pName, pName, 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 to create a function in which this code works automatically for all Divs, since the page can have more than 50 DIV with the class "nomep xx". In the above example, it works correctly only for the DIV with class "pName".
If I do not use the class "name xx" it only takes the first selector it finds from ". listing . item-listing . info-product" and inserts the same characters into all Divs, which is not what I want.
When does the function
firstnomep
is called?– Leite
At the end of every script with a $(Function(){firstnomep()}); As I said, the code works...
– André Silva
Didn’t give...I think maybe it’s something with the function each.....
– André Silva
But I couldn’t figure out the reason for creating multiple classes with numbers in sequence. It would make more sense for all elements to have the same class. If you are giving a different class name to the elements to identify them separately, you are going the wrong way.
– Sam
I’m almost understand the function of the codes, but I think I need to explain a little more clearly.
– Sam
Usually we use it
ids
different to differentiate one element from the other when both have different properties. Equal elements, we use the sameclass
.– Sam
So I created the classes in sequence, because the selector was the same for all DIVS. In this case, the DIV repeats with the same selector more than 50x on the page. I thought that if I had in each of these 50DIVs a different class it would be easier to run the code, but I couldn’t... .
– André Silva
To better understand: The insertion of characters would be different in each DIV. In this case I was able to make the code, but the characters of the first selector he picks repeat for all inserts. To make it easier to understand, this is a virtual store, in this case, they are product names.. these products have very long names, so I’m taking the first and second word for playing above the name and leaving the name diminished with "..." Thanks for the dvd aid!
– André Silva
You don’t need to give a different id or class to each div. You can select all of the N ways and change one by one.
– Sam
Did the answer of Leite work? I was making an example here but if it worked, blz.
– Sam
It worked well dvd and exactly as you said. I didn’t need to create the classes...!
– André Silva