Search code examples
javascriptstringprototypejsgetelementbyid

Prototype function different id elements of the same class


I'm making this prototype script to work:

function removing () {
*var ids = $$('.class').collect(function(el) { return el.id; });* //array of ids, not used by now
var data = $$('.class').pluck('innerHTML');
var wanted_count = 10;
var output = cutHtmlString(data, wanted_count);
$$('.class').invoke('replace', output + '...');
}

on this markup:

<div class="class" id="id1">content 1</div>
<div class="class" id="id2>content 2</div>
<div class="class" id="id3>content 3</div>

cutHtmlString is a function that cut html strings keeping tags and I want to apply it to every different div content. I create 'data' variable (by innerHTML) from general $$(.class) and then I execute cutting by a words count (var wanted_count) into 'output' var.
At the end I replace the original element (by $$.class again) with its new cut content.

All works great except for one issue: using only $$(class) makes only the first element content to be considered and replaced to every others.
I need to identify elements by ids too, I guess..thus I added the commented function upon (collect) but I don't know how to join my target..

By now I only got to this results:

this is the content of firts 'class' div...(cut)
this is the content of firts 'class' div...
this is the content of firts 'class' div...

while I want to get:

this is the content of first 'class' div...
this is the content of second 'class' div...
this is the content of third 'class' div...

thanks guys and an appreciation to this great community whole


Solution

  • I believe you are mixing working on a collection of elements with working on a single element. It's been a while since I've been in Prototype, but have you tried to work on very individually so output is scoped to the element you are replacing:

    function removing () {
      var data, output, wanted_count = 10;
    
      $$('.class').each(function(element){
        output = cutHtmlString(element.innerHTML, wanted_count);
        element.replace(output + '...');
      });
    }