Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery: Check against first instance

Having some trouble with this with taking a weird output and turning it into readable screenplay format.

So here is the HTML.

<div>
<p class="actor">John</p>
<p class="line">I want to buy milk.</p>
<p class="actor">John</p>
<p class="line">Milk is expensive.</p>
<p class="dirNote">John grabs the milk</p>
<p class="actor">John</p>
<p class="line">I guess its fine.</p>
<p class="actor">Steve</p>
<p class="line">Yeah.</p>
</div>

My attempts have solving this have failed. but the basic idea is this...

loop through each instance of p.actor
store first instance as a var

check next instance against var

if they are the same

append contents of that instance's p.line into the p.line of var

else replace var

with new p.actor

Also, if encounter a p.dirNote next instance of p.actor sets new var

basically when finished the html should look like this

<div>
<p class="actor">John</p>
<p class="line">I want to buy milk. Milk is expensive.</p>
<p class="dirNote">John grabs the milk</p>
<p class="actor">John</p>
<p class="line">I guess its fine.</p>
<p class="actor">Steve</p>
<p class="line">Yeah.</p>
</div>

Any thoughts on feasibility? Thank you.

like image 303
user2859646 Avatar asked Jun 06 '26 16:06

user2859646


1 Answers

The following snippet should do trick. It basically coverts the collection into an array and starts from the last element in the set.

$('p.actor').toArray().reverse().forEach(function (el) {
    var 
        $this = $(el), 
        $prev = $this.prev().prev('.actor'), 
        $line
    ;

    if ($this.text() !== $prev.text()) {
        return;
    }

    $line = $this.next('.line');
    $prev.next('.line').append(' ' + $line.text());
    $this.add($line).remove();
});

http://jsfiddle.net/j9qwzyzq/

like image 171
undefined Avatar answered Jun 08 '26 10:06

undefined



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!