JQuery: checking first instance

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

So here's 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 to solve this have failed. but the main idea is ...

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

check next instance for var

if they are the same

add the content of this p.line instance to p.line var

else replace var

with new p.actor

Also, if p.dirNote is encountered, the next instance of p.actor sets a new var

basically on completion 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.

+3


source to share


2 answers


The next snippet should do the trick. It basically hides the collection in the array and starts at the last item 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/

+2


source


I have a semi-answer for you. He has become more developed than me, so I will stop now.

It looks at your paragraphs, keeps track of their type, and rebuilds the new list. It is still necessary to figure out how to properly track the previous (or next) line / actor and addRow

. Hope this helps ...



var rows = $("#my-list p"),
newRows = [],
currentActor = null,
currentLine = null,
addRow = function (type, value) {
    newRows.push({
        type: type,
        value: value
    })
};

rows.each(function (index) {
    var $row = $(this),
        className = $row.attr("class"),
        isActor = className == "actor",
        isLine = className == "line",
        isDirNote = className == "dirNote",
        content = $row.text();

    if (isLine) {
        //TODO: keep track of line to be appended to next item (if same actor)
        //TODO: if next element is same actor, append line
        //addRow(className, content);
    }
    if (isDirNote || isActor) {
        addRow(className, content);
    }
    console.log(content, isActor, isLine, isDirNote);
})

console.log(newRows);

//TODO: build new paragraph array from newRows

      

0


source







All Articles