(Adding and) Removing list items with JavaScript / jQuery - javascript

I am almost a noob at JavaScript and jQuery, (so I apologize if I didn't recognize a suiting answer to my question, in similar posts).
Here is the thing. I have a list with lots of stuff in each list item:
<ul id="fruit_list">
<li>
<h4> Fruit 1: remove </h4>
<p> blablabla </p>
</li>
<li>
<h4> Fruit 2: remove </h4>
<p> blablabla </p>
</li>
</ul>
add
What I want to do, is when I click on the anchor 'remove', to remove the list item containing it.
(Optionally I would like to manipulate the incremental number at Fruit 1, Fruit 2 etc, in a way that when I remove item #2, then the next one becomes the #2 etc. But anyway.)
So here is what I've written so far:
$(function(){
var i = $('#fruit_list li').size() + 1;
$('a.add').click(function() {
$('<li><h4>Fruit '+i+':<a href="#" class="remove">
remove</a></h4><p>Blabla</p></li>')
.appendTo('#fruit_list');
i++;
});
$('a.remove').click(function(){
$(this).parentNode.parentNode.remove();
/* The above obviously does not work.. */
i--;
});
});
The 'add' anchor works as expected. The 'remove' drinks a lemonade..
So, any ideas?
Thanks
EDIT: Thanks for your answers everybody!
I took many of your opinions into account (so I won't be commenting on each answer separately) and finally got it working like this:
$('a.remove').live('click', function(){
$(this).closest('li').remove();
i--;
});
Thank you for your rapid help!

The a.remove event binding needs to be a live http://api.jquery.com/live/ binding. The nodes are added to the DOM after doc ready is called.
Additionally, I think you want to use parent() instead of parentNode. Unless I'm behind on my jQuery, parentNode is just DOM manipulation and there's no standard remove(), it's removeChild(). Here you need a jQuery collection returned from parent().

Try $(this).parents("LI").remove();

The reason is that $('a.remove') is only executed once, and so only found at the moment you don't have any remove links yet. To solve this rewrite your ADD function like this:
$('a.add').click(function() {
var $li = $('<li><h4>Fruit '+i+':<a href="#" class="remove">
remove</a></h4><p>Blabla</p></li>');
$li.appendTo('#fruit_list');
$li.find('a.remove').click(function() {
$li.remove();
i--;
});
i++;
});
And just remove your old remove function.
EDIT: Oh, this will only work for items you add, if you already load some list items in the html before any Javascript is executed add this function under the $('a.add').click:
$('a.remove').click(function(){
$(this).parent().parent().remove();
i--;
});

Related

DOM Manipulations

I'm still struggling with this question.
Add an Event Handler to the li element and console.log() the name of the shirt they selected. Use JavaScript
<h3>Shirts</h3>
<ul id='list'>
<li>Biker Jacket</li>
<li>Mens Shirt</li>
</ul>
If i get your question right, use jQuery:
$('li').click(function() {
console.log($(this).text());
});
It looks like this is a homework question. And that you are new to StackOverflow.
On StackOverflow you should always write pieces of code that you have attempted.
Anyways, because you are new... I can show you 2 ways of accomplishing this.
Please note that I am not so good in vanilla Javascript aswell. So
there is probably a better way to accomplish what you're trying.
1) Inline Event Handler
You can add inline event handlers directly to the HTML, like this:
<h3>Shirts</h3>
<ul id='list'>
<li onclick='console.log(this.innerText)'>Biker Jacket</li>
<li onclick='console.log(this.innerText)'>Mens Shirt</li>
</ul>
2) Non-inline Event Handler
The difference here is that you need to refer to the exact elements you want to add an Event Listener to. The benefit of doing this, is that you don't have to add an Event Listener manually to each list element. So the HTML stays clean.
var list = document.getElementById("list"); // select the parent element
var items = list.getElementsByTagName("li"); // select all <li> items in this parent element
for (var i = 0; i < items.length; i++) { // loop through all items
items[i].addEventListener("click", function() { // add the click event listener to the item
console.log(this.innerText); // console.log() the item's text.
});
}
Also read the following MDN documentations to learn about the used functions:
getElementById
getElementByTagName
Loops and iterations
innerText
Happy learning!

Create unique buttons dynamically

I'm new to jQuery and am trying to create jQuery UI buttons dynamically and them to a list. I can create one list item but no more are appended after it. What am I doing wrong?
$('#buttonList').append('<li><button>'+ username + '</button>')
.button()
.data('type', userType)
.click(function(e) { alert($(this).data('type')); })
.append('<button>Edit</button></li>');
<div>
<ul id="buttonList">
</ul>
</div>
This only creates one list item with two buttons (although the second button seems to be encased in the first one, but I can probably figure that issue out). How do I get it to create multiple list items with their own unique 'data' values (i.e. I can't do a find() on a particular button class and give it data values as all buttons would then have the same data)?
I suggest to exchange the position of what you are appending and where you are appending to. This way, you retain the appended object, and should be able to work with it as a standard jQuery selector. From your code i commented out the .button() and the .append() lines, because i'm not sure what you want to do with them. Should you need help adding those lines, just drop a comment to my answer ;)
Oh, i almost forgot: i use var i to simulate different contents for username and userType data.
A JSFiddle for you is here: http://jsfiddle.net/cRjh9/1/
Example code (html part):
<div>
<p id="addButton">add button</p>
<ul id="buttonList">
</ul>
</div>
Example code (js part):
var i = 0;
$('#addButton').on('click', function()
{
$('<li><button class="itemButton">'+ 'username' + i + '</button></li>').appendTo('#buttonList')
//.button()
.find('.itemButton')
.data('type', 'userType'+i)
.click(function(e) { alert($(this).data('type'));
})
//.append('<button>Edit</button></li>')
;
i++;
});
You need complete tags when you wrap any html in a method argument. You can't treat the DOM like a text editor and append a start tag, append some more tags and then append the end tag.
Anything insterted into the DOM has to be complete and valid html.
You are also not understanding the context of what is returned from append(). It is not the element(s) within the arguments it is the element collection you are appending to. You are calling button() on the whole <UL>.
I suggest you get a better understanding of jQuery before trying to chain so many methods together
Just a very simplistic approach that you can modify - FIDDLE.
I haven't added the data attributes, nor the click function (I'm not really sure I like the
inline "click" functions - I generally do them in jQuery and try to figure out how to make
the code efficient. Probably not very rational, but I'm often so).
JS
var names = ['Washington', 'Adams', 'Jefferson', 'Lincoln', 'Roosevelt'];
for( r=0; r < names.length; r++ )
{
$('#buttonList').append('<li><button>'+ names[r] + '</button></li>');
}
$('#buttonList').append('<li><button>Edit</button></li>');

Skip recursion in jQuery.find() for a selector? [duplicate]

This question already has answers here:
jQuery: find() children until a certain threshold element is encountered
(5 answers)
Closed 16 days ago.
TL;DR: How do I get an action like find(), but block traversal (not full stop, just skip) for a certain selector?
ANSWERS: $(Any).find(Selector).not( $(Any).find(Mask).find(Selector) )
There were many truly great answers, I wish I could some how distribute the bounty points more, maybe I should make some 50 pt bounties in response to some of these ;p I choose Karl-André Gagnon's because this answer managed to make findExclude unrequired in one, slightly long, line. While this uses three find calls and a heavy not filter, in most situations jQuery can use very fast implementation that skips traversal for most find()s.
Especially good answers are listed below:
falsarella: Good improvement on my solution, findExclude(), best in many situatoins
Zbyszek: A filter-based solution similar to falsarella's, also good on efficiency
Justin: A completely different, but manageable and functional solution to the underlaying issues
Each of these have their own unique merits and and are deserving of some mention.
I need to descend into an element fully and compare selectors, returning all matched selectors as an array, but skip descending into the tree when another selector is encountered.
Edit: replacing original code sample with some from my site
This is for a message forum which may have reply message-groups nested inside any message.
Notice, however, we cannot use the message or content classes because the script is also used for other components outside of the forum. Only InterfaceGroup, Interface and controls classes are potentially useful - and preferably just Interface and controls.
Interact with the code and see it in JS Fiddle, thanks Dave A, here Click on the buttons while viewing a JavaScript console to see that the controls class is being bound to one extra time per level of .Interface nesting.
Visual A, Forum Layout Struture:
<li class="InterfaceGroup">
<ul class="Interface Message" data-role="MessagePost" >
<li class="instance"> ... condensed ... </li>
<li class="InterfaceGroup"> ... condensed ...</li>
</ul>
<ul class="Interface Message" data-role="MessagePost" >
<li class="instance"> ... condensed ... </li>
</ul>
<ul class="Interface Message" data-role="MessagePost" >
<li class="instance"> ... condensed ... </li>
<li class="InterfaceGroup"> ... condensed ...</li>
</ul>
</li>
Inside of each <li class="InterfaceGroup"> there could be any number of repetitions of the same structure (each group is a thread of messages) and/or deeper nesting such as..
<li class="InterfaceGroup">
<ul class="Interface Message" data-role="MessagePost" >
<li class="instance"> ... condensed ... </li>
<li class="InterfaceGroup">
<ul class="Interface Message" data-role="MessagePost" >
<li class="instance"> ... condensed ... </li>
<li class="InterfaceGroup"> ... condensed ...</li>
</ul>
</li>
</ul>
</li>
Inside of each <li class="instance"> ... </li> there are arbitrary places decided by another team where class="controls" may appear and an event listener should be bound. Though these contain messages, other components structure their markup arbitrarily but will always have .controls inside of .Interface, which are collected into an .InterfaceGroup.A reduced-complexity version of the inner-content (for forum posts) is below for reference.
Visual B, Message Contents with controls class:
<ul class="Interface Message" data-role="MessagePost" >
<li class="instance">
<ul class="profile"> ...condensed, nothing clickable...</ul>
<ul class="contents">
<li class="heading"><h3>Hi there!</h3></li>
<li class="body"><article>TEST Message here</article></li>
<li class="vote controls">
<button class="up" data-role="VoteUp" ><i class="fa fa-caret-up"> </i><br/>1</button>
<button class="down" data-role="VoteDown" >0<br/><i class="fa fa-caret-down"> </i></button>
</li>
<li class="social controls">
<button class="reply-btn" data-role="ReplyButton" >Reply</button>
</li>
</ul>
</li>
<li class="InterfaceGroup" > <!-- NESTING OCCURRED -->
<ul class="Interface Message" data-role="MessagePost" >
<li class="instance">... condensed ... </li>
<li class="InterfaceGroup" >... condensed ... </li>
</ul>
</li>
</ul>
We can only bind to controls that are within an Interface class, instance may or may not exist but Interface will. Events bubble to .controls elements and have a reference to the .Interface which holds them..
So I am trying to $('.Interface').each( bind to any .controls not inside a deeper .Interface )
That's the tricky part, because
.Interface .controls will select the same .control multiple times in the .each()
.not('.Interface .Interface .controls') cancels out controls in any deeper nesting
How can I do this using jQuery.find() or a similar jQuery method for this?
I have been considering that, perhaps, using children with a not selector could work and could be doing the same thing as find under the hood, but I'm not so sure that it actually is or wont cause horrible performance. Still, an answer recursing .children effectively is acceptable.
UPDATE: Originally I tried to use a psuedo-example for brevity, but hopefully seeing a forum structure will help clarify the issue since they're naturally nested structures. Below I'm also posting partial javascript for reference, line two of the init function is most important.
Reduced JavaScript partial:
var Interface=function()
{
$elf=this;
$elf.call=
{
init:function(Markup)
{
$elf.Interface = Markup;
$elf.Controls = $(Markup).find('.controls').not('.Interface .controls');
$elf.Controls.on('click mouseenter mouseleave', function(event){ $elf.call.events(event); });
return $elf;
},
events:function(e)
{
var classlist = e.target.className.split(/\s+/), c=0, L=0;
var role = $(e.target).data('role');
if(e.type == 'click')
{
CurrentControl=$(e.target).closest('[data-role]')[0];
role = $(CurrentControl).data('role');
switch(role)
{
case 'ReplyButton':console.log('Reply clicked'); break;
case 'VoteUp':console.log('Up vote clicked'); break;
case 'VoteDown':console.log('Down vote clicked'); break;
default: break;
}
}
}
}
};
$(document).ready( function()
{
$('.Interface').each(function(instance, Markup)
{
Markup.Interface=new Interface().call.init(Markup);
});
} );
If you want to exclude element in you find, you can use a not filter. As for example, I've taken you function that exclude element and made it way shorter :
$.fn.findExclude = function( Selector, Mask,){
return this.find(Selector).not(this.find(Mask).find(Selector))
}
Now, ill be honest with you, I did not fully understand what you want. But, when i took a look at your function, I saw what you were trying to do.
Anyway, take a look at this fiddle, the result is the same as your : http://jsfiddle.net/KX65p/8/
Well, I really don't want to be answering my own question on a bounty, so if anyone can provide a better or alternative implementation please do..
However, being pressed to complete the project, I ended up working on this quite a bit and came up with a fairly clean jQuery plugin for doing a jQuery.find() style search while excluding child branches from the results as you go.
Usage to work with sets of elements inside nested views:
// Will not look in nested ul's for inputs
$('ul').findExclude('input','ul');
// Will look in nested ul's for inputs unless it runs into class="potato"
$('ul').findExclude('input','.potato');
More complex example found at http://jsfiddle.net/KX65p/3/ where I use this to .each() a nested class and bind elements which occur in each nested view to a class. This let me make components server-side and client-side reflect each other's properties and have cheaper nested event handling.
Implementation:
// Find-like method which masks any descendant
// branches matching the Mask argument.
$.fn.findExclude = function( Selector, Mask, result){
// Default result to an empty jQuery object if not provided
result = typeof result !== 'undefined' ?
result :
new jQuery();
// Iterate through all children, except those match Mask
this.children().each(function(){
thisObject = jQuery( this );
if( thisObject.is( Selector ) )
result.push( this );
// Recursively seek children without Mask
if( !thisObject.is( Mask ) )
thisObject.findExclude( Selector, Mask, result );
});
return result;
}
(Condensed Version):
$.fn.findExclude = function( selector, mask, result )
{
result = typeof result !== 'undefined' ? result : new jQuery();
this.children().each( function(){
thisObject = jQuery( this );
if( thisObject.is( selector ) )
result.push( this );
if( !thisObject.is( mask ) )
thisObject.findExclude( selector, mask, result );
});
return result;
}
Maybe something like this would work:
$.fn.findExclude = function (Selector, Mask) {
var result = new jQuery();
$(this).each(function () {
var $selected = $(this);
$selected.find(Selector).filter(function (index) {
var $closest = $(this).closest(Mask);
return $closest.length == 0 || $closest[0] == $selected[0] || $.contains($closest, $selected);
}).each(function () {
result.push(this);
});
});
return result;
}
http://jsfiddle.net/JCA23/
Chooses those elements that are either not in mask parent or their closest mask parent is same as root or their closest mask parent is a parent of root.
I think that this is the closest the findExclude can be optimized:
$.fn.findExclude = function (Selector, Mask) {
var result = $([]);
$(this).each(function (Idx, Elem) {
$(Elem).find(Selector).each(function (Idx2, Elem2) {
if ($(Elem2).closest(Mask)[0] == Elem) {
result = result.add(Elem2);
}
});
});
return result;
}
Also, see its fiddle with added logs with ellapsed time in milliseconds.
I see that you are worried with the performances. So, I've run some tests, and this implementation takes no longer than 2 milliseconds, while your implementation (as the answer you have posted) sometimes takes around 4~7 millisecods.
From my understanding, I would bind to the .controls elements and allow the event to bubble up to them. From that, you can get the closest .Interface to get the parent, if needed. This way you are added multiple handlers to the same elements as you go further down the rabbit hole.
While I saw you mention it, I never saw it implemented.
//Attach the event to the controls to minimize amount of binded events
$('.controls').on('click mouseenter mouseleave', function (event) {
var target = $(event.target),
targetInterface = target.closest('.Interface'),
role = target.data('role');
if (event.type == 'click') {
if (role) {
switch (role) {
case 'ReplyButton':
console.log('Reply clicked');
break;
case 'VoteUp':
console.log('Up vote clicked');
break;
case 'VoteDown':
console.log('Down vote clicked');
break;
default:
break;
}
}
}
});
Here is a fiddle showing what I mean. I did remove your js in favor of a simplified display.
It does seem that my solution may be a over simplification though...
Update 2
So here is a fiddle that defines some common functions that will help achieve what you are looking for...I think. The getInterfaces provides a simplified function to find the interfaces and their controls, assuming all interfaces always have controls.
There are probably fringe cases that will creep up though. I also feel I need to apologize if you have already ventured down this path and I'm just not seeing/understanding!
Update 3
Ok, ok. I think I understand what you want. You want to get the unique interfaces and have a collection of controls that belong to it, that make sense now.
Using this fiddle as the example, we select both the .Interface and the .Interface .controls.
var interfacesAndControls = $('.Interface, .Interface .controls');
This way we have a neat collection of the interfaces and the controls that belong to them in order they appear in the DOM. With this we can loop through the collection and check to see if the current element has the .Interface associated with it. We can also keep a reference to the current interface object we create for it so we can add the controls later.
if (el.hasClass('Interface')){
currentInterface = new app.Interface(el, [], eventCallback);
interfaces.push(currentInterface);
//We don't need to do anything further with the interface
return;
};
Now when we don't have the .Interface class associate with the element, we got controls. So let's first modify our Interface object to support adding controls and binding events to the controls as they are being added to the collection.
//The init function was removed and the call to it
self.addControls = function(el){
//Use the mouseover and mouseout events so event bubbling occurs
el.on('click mouseover mouseout', self.eventCallback)
self.controls.push(el);
}
Now all we have to do is add the control to the current interfaces controls.
currentInterface.addControls(el);
After all that, you should get an array of 3 objects (interfaces), that have an array of 2 controls each.
Hopefully, THAT has everything you are looking for!
If I understand you:
understanding your needs better and applying the specific classes you need, I think this is the syntax will work:
var targetsOfTopGroups = $('.InterfaceGroup .Interface:not(.Interface .Interface):not(.Interface .InterfaceGroup)')
This Fiddle is an attempt to reproduce your scenario. Feel free to play around with it.
I think I found the problem. You were not including the buttons in your not selector
I changed the binding to be
var Controls = $('.InterfaceGroup .Interface :button:not(.Interface .Interface :button):not(.Interface .InterfaceGroup :button)');
Fiddle
Why not taking the problem upside down?
Select all $(.target) elements and then discard them from further treatment if their .$parents(.group) is empty, that would give sonething like:
$('.target').each(function(){
if (! $(this).parents('.group').length){
//the jqueryElem is empy, do or do not
} else {
//not empty do what you wanted to do
}
});
Note that don't answer the title but literally gives you "Selector B, inside of a result from Selector A"
If your .interface classes had some kind of identifier this would seem to be rather easy.
Perhabs you already have such an identifier for other reasons or choose to include one.
http://jsfiddle.net/Dc4dz/
<div class="interface" name="a">
<div class="control">control</div>
<div class="branch">
<div class="control">control</div>
<div class="interface">
<div class="branch">
<div class="control">control</div>
</div>
</div>
</div>
<div class="interface" name="c">
<div class="branch">
<div class="control">control</div>
</div>
</div> </div>
$( ".interface[name=c] .control:not(.interface[name=c] .interface .control)" ).css( "background-color", "red" );
$( ".interface[name=a] .control:not(.interface[name=a] .interface .control)" ).css( "background-color", "green" );
Edit: And now Im wondering if you're tackling this problem from the wrong angle.
So I am trying to $('.Interface').each( bind to any .controls not
inside a deeper .Interface )
http://jsfiddle.net/Dc4dz/1/
$(".interface").on("click", ".control", function (event) {
alert($(this).text());
event.stopPropagation();
});
The event would be triggered on a .control; it would then bubble up to its .closest( ".interface" ) where it would be processed and further propagation be stopped. Isn't that what you described?

Jquery select all children within children

I'm sure this will be a simple question but I still struggle with DOM selectors in Jquery so here is a model of my html code:
<fieldset class="product-options" id="product-options-wrapper">
<ul class="options-list">
<li><a href>Item1.1</a></li>
<li><a href>Item1.2</a></li>
<li><a href>Item1.3</a></li>
</ul>
...other html items here
<ul class="options-list">
<li><a href>Item2.1</a></li>
<li><a href>Item2.2</a></li>
<li><a href>Item2.3</a></li>
</ul>
</fieldset>
Now how do I select all of the 'li a' items in both lists (or X number of lists) with class name .options-list and bind them with a click function.
Currently I have:
$('fieldset#product-options-wrapper ul.options-list > li a').bind('click', function(e) {
//code here
});
And it only gets the first options-list.
Thanks, greatly appreciated!
EDIT: If i click on a Item2.X list item first, then it will grab that options list. But as soon as I click on the Item1.x list items it disregards the second .options-list
If you are going to bind to each li element, you should bind it to the ul element instead (helps greatly with performance when there are a lot of events).
$('.options-list', '#product-options-wrapper').bind('click', function(e)
{
e.preventDefault();//In case you don't want to go to a different page
var clicked = e.target;//The href that was clicked
/* If you only want this to happen if the a tag was clicked, add the following line
if(clicked.tagName == 'A')*/
//Rest here
});
How about $('.options-list a').bind('click', function(e) { });?
You can use delegate in this case to make it even simpler. Try this
$('#product-options-wrapper ul.options-list').delegate('li > a', 'click', function(e) {
//code here
});
Your method seems sound to me. I created a test fiddle using your HTML (and an extra anchor to prove that it won't get the click added) and your JS (with minor modifications).
http://jsfiddle.net/chrisvenus/esZxH/1/
The selector you had did work but since you said you wanted the a to be a direct child of the li (or at least I read it that way) I slightly tweaked it in my version above. ARe you sure its not just your function is not doing quite what you want while executing or can you confirm that your click function isn't being run at all?

multiple selectors not seems to work

I have following HTML
<div id="finalTree">
<ul>
<li class="last" style="display: list-item;">
<a id="DataSheets" href="#">Data Sheets</a>
</li></u>...........</div>
and I am first hiding all these li and then trying to show those li which match to selector. Here is my JavaScript. Here filterData is id of links.
function filterLeftNavTree(filterData){
jQuery("ul.treeview").find("li").hide();
var selectors =[];
if(filterData.indexOf("|")!=-1){
var filterData = filterData.split("|");
for(i=0;i<filterData.length;i++){
selectors.push('#'+filterData[i]);
}
var filtered = selectors.join(',');
$(filtered ).show();
}else{
$('#'+filterData+).show();
} }
the last two line doesn't works...
any one can tell me what can be possible reason. Actually I tried to show li with :has, :contains, find().filter() but all these are taking too much time if I have large tree.
Do I am trying to show it by using multiple selector, but it's not showing any thing. Any alternative having faster way to show it will be highly appreciated.
What you have (aside from the syntax error #verrerby mentioned) should be working, but why not cut down on that code a bit?
You can slim things down by adding the # on every element after the first as part of the .join(), this also greatly simplifies the logic. You can reduce it down to:
function filterLeftNavTree(filterData) {
$("ul.treeview li").hide();
$('#'+filterData.split('|').join(',#')).show();
}
Also note the change removing .find(), it's faster in browser that support it to use a single selector, and just as fast in all the others.
The only other possible reason I see for your code not working is jQuery is used for the hide and $ is used on the show, is it possible $ refers to something else? (e.g. ptototype?) To test just replace $ with jQuery on the .show() call.
You have an extra +' in the last statement, and you could do it in multiple statements instead of one (the #{id} selector is very fast):
if(filterData.indexOf("|")!=-1){
var filterData = filterData.split("|");
for(i=0;i<filterData.length;i++){
$('#'+filterData[i]).show();
}
}else{
$('#'+filterData).show();
}

Categories