Jgunzblazin
Jgunzblazin

Reputation: 135

Append element to single element of array

Having trouble where my ‘p’ element value is being appended to both ‘review-comment-wrap’ blocks. I think the issue may be that in my append function the 'p' element is being appended to all the review-comment-wrap elements. How do I append only to the 'review-comment-wrap' block where the element with the value B was removed?

<div class="reviewer-meta">
    <div class="author-attribute">Value A</div>
    <div class="author-attribute">Value B</div>
</div>

<div class="review-comment-wrap">some value</div>
/** add appended value here only **/

<div class="reviewer-meta">
    <div class="author-attribute">Value A</div>
</div>

<div class="review-comment-wrap">some value</div>


function runProgram(){
    var theElements = $('.reviewer-meta').find('.author-attribute');

    $(theElements).each(function(){
        if(this.innerHTML == "Value B"){
            $(this).remove();   
        }
    });
    $('.review-comment-wrap').append('<p>New value</p>');
}
runProgram();

Upvotes: 1

Views: 67

Answers (3)

cesare
cesare

Reputation: 2118

To get the element "review-comment-wrap" that is very next at the reviewer-meta where your check results true you can use 'next()' function applied at the parent element.

function runProgram(){
var theElements = $('.reviewer-meta').find('.author-attribute');

$(theElements).each(function(){
   if(this.innerHTML == "Value B"){
       $(this).parent().next('.review-comment-wrap').append('<p>New value</p>');
    $(this).remove();   
}
});

}
runProgram();

Further info: https://api.jquery.com/next/

Upvotes: 1

DACrosby
DACrosby

Reputation: 11430

You need to move the append into the if statement and refer to that group of elements.

function runProgram(){
    var theElements = $('.reviewer-meta').find('.author-attribute');

    $(theElements).each(function(){
        if(this.innerHTML == "Value B"){
            $(this).siblings('.review-comment-wrap').append('<p>New value</p>');
            $(this).remove();
        }
    });
}

http://jsfiddle.net/daCrosby/a0orn0q7/

If you want to streamline a bit more, you can make use of the filter function as well. This allows you to skip the loop and if statements entirely.

function runProgram(){
    var element = $('.reviewer-meta').find('.author-attribute')
                     .filter( function(){ return $(this).text() == "Value B"; });

    element.siblings('.review-comment-wrap').append('<p>New value</p>');
    element.remove();
}
runProgram();

http://jsfiddle.net/daCrosby/a0orn0q7/1/

Upvotes: 1

Ethan Green
Ethan Green

Reputation: 71

I agree that is does need to go inside the loop, however you need to farther refine the jquery select statement.

I would use something like

$(theElements).each(function(){ if(this.innerHTML == "Value B"){ $(this).parent().appaend('<p>New value</p>'); $(this).remove();
} });

Upvotes: 0

Related Questions