2

I'm simply just trying to push the text of an li element when I click the add button. But when I click my add button, it is pushing all the items in my list to the array. I guess it's because I'm just using a class. What would be the best way around this? Thanks in advance!

HTML

<div id="products">
    <ul>
        <li><p>Lorem 1</p><button class="target">Add</button></li>
        <li><p>Lorem 2</p><button class="target">Add</button></li>
    </ul>
</div>

jQuery

$(document).ready(function(){
    var array = Array();
    $(".target").click(function() {
        $('p').each(function (i, e) {
              array.push($(e).text());  
        });
        console.log(array);
    });
});
2
  • $('p') selects all p elements. You want to select only the one that came before the clicked element. .prev Commented Mar 25, 2013 at 15:40
  • Do you want to be able to add it more than once? Commented Mar 25, 2013 at 15:41

3 Answers 3

3

How about this:

$(document).ready(function(){

    var array = []; //Use the bracket notation instead.

    $(".target").click(function(e) {
        var p = $(this).closest('li').find('p');
        array.push(p.text());

        console.log(array);
    });
});

Basically you want to find the closest li enclosing your .target (the one which was clicked) and then find the paragraph contained in that li.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @kgr , that's exactly what I've been looking for, thank you very much!
.prev() may be more appropriate than closest/find here.
@Mark is right, prev or siblings might be better (simpler) but I meant to show the idea of using this and traversing DOM from that.
0
$(document).ready(function(){

    var array = [];

    $(".target").click(function() {
        array.push($(this).siblings('p').text()); //Replace with this and it will get the text from clicked li only.
        console.log(array);
    });
});

2 Comments

I don't think it will, $(this) will be the button, not the li.
the button doesn't have any child p elements.
0

Your javascript code essentially says:

When an element of the class "target" is clicked, push EACH of the paragraph elements text to the array.

Consider replacing this:

$('p').each(function (i, e) {
    array.push($(e).text());    
});

with:

array.push($(this).previousSibling.text());

This will instead add the text value only from the paragraph element which immediately preceded the button that the user clicked.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.