Reputation: 1880
I have following html list:
<ul>
<li class="list-group-item ReplyPill">This is my first value<span class="badge badge-pill"><div id="close">X</div></span></li>
<li class="list-group-item ReplyPill">This is my second value<span class="badge badge-pill"><div id="close">X</div></span></li>
(...)
</ul>
and I am using this jQuery to get all 'li' elements:
let replyOptions = [];
$('.ReplyPill').each(function () {
replyOptions.push($(this).text());
});
The problem is that the "X" from the 'div' is also read and my output looks like this: "This is my first valueX"
I already tried ".not('#close')" to exclude the div, but it did not change anything.
So is there a way to ignore the 'div' with the id "close" in the loop?
Upvotes: 2
Views: 362
Reputation: 178285
IDs need to be unique - you need a class instead
Also DIV is not a valid child of a span
Anyway
let replyOptions = $('.ReplyPill').map(function() {
return $(this).contents().get(0).nodeValue;
}).get();
console.log(replyOptions);
// PS how to delegate the click on the X
$("#list").on("click",".close",function() {
$(this).closest("li").hide();
})
li {
width: 200px;
background-color: yellow;
}
.badge {
display: inline-block;
float: right;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="list">
<li class="list-group-item ReplyPill">This is my first value<span class="badge badge-pill close">X</span></li>
<li class="list-group-item ReplyPill">This is my second value<span class="badge badge-pill close">X</span></li>
</ul>
Upvotes: 3
Reputation: 337626
Exclusions in selectors are a little tricky, especially when dealing with text nodes. A simpler approach would be to wrap the text you want to retrieve in its own element and target it directly.
Also note that it's invalid HTML to place div
elements inside span
. In addition, you can use map()
to build your array more effectively. Try this:
let replyOptions = $('.ReplyPill span.value').map((i, el) => el.textContent).get();
console.log(replyOptions);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
<li class="list-group-item ReplyPill">
<span class="value">This is my first value</span>
<span class="badge badge-pill close">X</span>
</li>
<li class="list-group-item ReplyPill">
<span class="value">This is my second value</span>
<span class="badge badge-pill">X</span>
</li>
</ul>
Upvotes: 2