I am very close to solving this problem but I can't seem to grab the outer html from my <li>.
I am adding my <li>'s to a <ul> like this
function addTab() {
tabs.append('<li class="navHighlight">'
+ '<a href="#">'
+ title
+ '</a>'
+ '<a href="#">'
+ '<img src="images/delete.png" class="deleteImage"/>'
+ '</a>'
+ '</li>');
};
Then I'm trying to delete them with this
$("body").on("click", ".deleteImage", function (e) {
var removeItem = $(this).closest('li').html(); // problem
console.log(removeItem);
listItems = jQuery.grep(listItems, function (value) {
console.log(value);
return value != removeItem;
});
});
But the problem is, my remove item variable has this value
Test<img src="images/delete.png" class="deleteImage" style="display: inline;">
and I need it to have the outer html value as well, like this
<li>Test<img src="images/delete.png" class="deleteImage"/></li>
the class value I initially assign to the <li> called "navHighlight" will of been removed by this time because it's only there for aesthetic purposes. It is toggled when another <li> item is clicked, so that point of reference is out the window. I've tried a lot of different things, but I can't seem to grab the outer html <li> tag.
Any help is appreciated.
You can use outerHTML to get the outside wrapper li as well:
var removeItem = $(this).closest('li')[0].outerHTML;
Related
I am creating and appending <li> elements to the DOM via jQuery whenever the user clicks a specific button. However, once they are added to the DOM, they appear as <li style=""></li>, in comparison to <li></li>. Why is this happening?
I understand that, visually, this doesn't cause a problem. However, it does cause a problem when trying to find a specific element's index in an array.
Function that adds the <li> element:
function addNewTask(input) {
let userInput;
userInput = input;
let task = '<li><span class="text-task">' + userInput + '</span><span class="delete-task">x</span></li>';
//parent = $('.task-list');
$('.task-list').append(task).children(':last').hide().fadeIn(250);
arr.push(task);
localStorage.setItem('items', JSON.stringify(arr));
console.log(arr);
}
Function that attempts to find array index of DOM element (currently not working as intended - it can not find the index by the specified value):
$(document).ready(function () {
$(document).on('click', '.delete-task', function () { // We use 'on' as the element is dynamically added
console.log("'Delete' button pressed");
var $self = $(this);
var index = this.parentElement.outerHTML;
var findIndex = arr.indexOf(index);
arr.splice(findIndex, 1);
$self.parent().fadeOut(250, function() {
console.log($self.parent().html());
$self.remove(); // Dynamically remove the DOM element from the list
localStorage.setItem('items', JSON.stringify(arr));
console.log(localStorage.getItem('items'));
});
});
});
HTML Expected Output:
<li><span class="text-task">' + userInput + '</span><span class="delete-task">x</span></li>
HTML Actual Output:
<li style=""><span class="text-task">' + userInput + '</span><span class="delete-task">x</span></li>
Update (Problem Solved!):
I was able to solve the problem by removing the style attribute once the .hide() and .fadeIn() jQuery methods had finished executing.
Modified code:
function addNewTask(input) {
let userInput;
userInput = input;
let task = '<li><span class="text-task">' + userInput + '</span><span class="delete-task">x</span></li>';
arr.push(task);
//parent = $('.task-list');
$('.task-list').append(task).children(':last').hide().fadeIn(250, function() {
console.log(this);
$(this).removeAttr('style');
localStorage.setItem('items', JSON.stringify(arr));
console.log(arr);
});
}
This is caused by your use of hide().fadeIn(250). Those methods set inline display and opacity CSS rules on the affected element. Once the transition completes the rules are removed, but the empty style attribute remains.
You can see this happening in the below snippet if you inspect the existing li element before clicking the button to add a new li:
function addNewTask(input) {
let task = '<li><span class="text-task">' + input + '</span><span class="delete-task">x</span></li>';
$('.task-list').append(task).children(':last').hide().fadeIn(250);
}
$('button').click(function() {
addNewTask('foobar');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="task-list">
<li>Foo</li>
</ul>
<button>Add</button>
If you wanted to remove the orphaned style attribute (even though it does no harm), you could call removeAttr() in the callback of fadeIn():
function addNewTask(input) {
let task = '<li><span class="text-task">' + input + '</span><span class="delete-task">x</span></li>';
$('.task-list').append(task).children(':last').hide().fadeIn(250, function() {
$(this).removeAttr('style');
});
}
$('button').click(function() {
addNewTask('foobar');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="task-list">
<li>Foo</li>
</ul>
<button>Add</button>
Using JavaScript and JQuery and underscore
Currently I have the following
<div id="select"></div>
which is populated by the following code
$(document).ready(function () {
$('.go img').css('cursor', 'pointer');
$('.go').on('click', 'img', function (e) {
$(this).width(100).height(100).appendTo('#select');
So at the moment only the img is taken and placed inside #select, but I would also like for it to include item.A item.C and item.C
But I'm not sure how to change the $(document).ready(function () { code block to achieve this?
I thought I might need to give the div an id and reference that?
I've been able to take the whole lot by concatenating the code block, but thats not how I want it to work, I'd like each element seperate so that I can target it with CSS.
_.each(Badges, function (item) {
var wrapper = $('<div class="wrapper"></div>');
wrapper.append('<img class="images BadgeImgOutline responsive-image" src="' + item.imageURL + '" />');
wrapper.append('<div>' + item.A + '</div>');
wrapper.append('<div>' + item.B + '</div>');
wrapper.append('<div>' + item.C + '</div>');
$('#container').append(wrapper);
});
You could use jQuerys ".parent()" method to get the parent of the img tag - in this case your wrapper div and add this to your select.
The code could look like so:
$(this).width(100).height(100);
$(this).parent().appendTo('#select');
for shrinking the image and appending the whole wrapper including img and items to your select.
Hope this helps
HTML string:
var ul = document.getElementById("list");
$("#list").append(
"<li class='margbottom'>" +
"<label id='id_'><img src='images/icon-approved1.png' class='imgspace' align='absmiddle'/><span id='categoriesName'>" + categoryName + "</span>: <span id='categoriesValue'>" + value + "</span></label>" +
"<div class='menuicon'>" +
"<ul>" +
"<li><a href='#url' onclick='removeCategory();'><img src='images/icon_minus.png'></a></li>" +
"<li><a href='#url'><img src='images/icon-searchby-s.png'></a></li>" +
"</ul>" +
"</div>" +
"</li>"
);
JS:
function removeCategory(){
alert("Inside removeCategory");
var elem = document.getElementById('list');
elem.parentNode.removeChild(elem);
}
I have created dynamically li list and I need to remove it dynamically. bt by calling removeCategory it is removing all element instead of particular one.
Anyone can help?
Thanks in Advance.
In this specific situation, you should pass this to the removeCategory function and use it as the element.
So, basically -
<a href='#url' onclick='removeCategory();'
Should be -
<a href='#url' onclick='removeCategory(this);'
And the function should be -
function removeCategory(elem){
alert("Inside removeCategory");
elem.parentNode.removeChild(elem);
}
However, adding HTML within the JavaScript like this is discouraged. If you must, at least do not use inline event listeners, but add them using jQuery instead ($("#list a").on("click", removeCategory); and then just use this within the updated function instead of elem).
Also, your code was indeed removing the entire list, because you are always removing the parent element of the element that has the list ID.
In jQuery you can do like this:
Add class 'removeLink' to your tag. No need for onClick() action.
jQuery code to remove:
$('removeLink').click(function(){
var iconDiv = $(this).closest('.menuicon');
var li = iconDiv.closest('<li>');
li.remove();
});
$("ul").find("[particular li selector]").remove();
The above is just a starting point. It all depends on how easy access you have to the particular li in question. You can either access it directly (by id) or via the parent in some way.
If possible do this
$("#particularLI").remove();
I have an application that reads the items stored in the localStorage and displays it in a <li /> when the page "loads".
The listview contains a split button that when pressed it removes the related item from the list; this is part of what I'm aiming for, looking around on the internet I have tried to find a way so this "delete/remove" function ALSO removes the selected item inside the <li /> from the localStorage, but for some reason my script below seems to remove random items.
$(document).ready(function () {
window.addEventListener('load', OnStorage, false);
});
function OnStorage(event) {
if (window.localStorage) {
var key, value;
// loop through local storage
for (var i = 0; i < localStorage.length; i++) {
// retrieve the key
key = localStorage.key(i);
// set the field from the key
value = localStorage.getItem(key);
$("#medListDiv").show();
var text = '<h2>' + value + '</h2>' + '<a href="#" class="del">Delete</a>';
$('<li />', {
html: text
}).appendTo('ul.medList');
}
$('ul.medList').listview('refresh')
}
}
//Deletes items from the medicine List
$('ul').on('click', '.del', function (el) {
$(this).closest('li').remove();
localStorage.removeItem(key); //Where problem relies
$('ul.medList').listview('refresh');
});
I believe it has to do with the key being the wrong one but can't work my head around a way to make the script take the right key from the selected item. Or if there is a way to remove the item by taking the value alone? (Doubt it as all I find can only be done by manipulating the key).
Please any suggestions will be greatly appreciated.
Store your key in an attribute of the anchor tag
var text = '<h2>' + value + '</h2>' + '<a href="#" key="'+key+'" class="del">Delete</a>';
$('<li />', {
html: text
}).appendTo('ul.medList');
and in click event refer that attribute
$('ul').on('click', '.del', function (el) {
$(this).closest('li').remove();
var key = $(this).attr('key');
localStorage.removeItem(key); //Where problem relies
$('ul.medList').listview('refresh');
});
hope this solves your problem.
you should get key value , where you are performing click event on ui.
let say every li is like
<li data='key'>....</li>
// key refrence to the name of key in localstorage
and when clicking on function you can get the key value like
var key = $(this).closest().attr("data");
localStorage.removeItem(key);
The Html that I'm getting ideally looks like this:
<span class="RapidLink1-H">See the more detailed areas of what not</span>
Next my aim is to change the span tag into an anchor tag. With the ideal Html, I have done it this way:
// Walk through each link tag on this page and replace the content with an actual link
thisLink.each(function() {
linkRefTarget = '';
// Get only the identifier number of the link
linkId = ($(this).attr('class')).replace(/[A-Za-z$-]/g, '');
// Match this link with the list of link references
if (thisLinkRef) {
for (var key in thisLinkRef) {
if (key == 'link' + linkId) linkRefTarget = thisLinkRef[key];
}
}
output = '';
output+= '<a href="#' + linkRefTarget + '" id="link' + linkId + '" class="rapidLink">';
output+= $(this).html();
output+= '</a>';
}).replaceWith(output);
Now, the problem comes when I'm actually getting this sort of Html (please note, I can't change the Html input):
<span class="RapidLink1-H">See the</span><span class="RapidLink1-H">more detailed areas of</span><span class="RapidLink1-H">what not</span></span>
The question is:
How could I get it to work with such a broken set of spans?
I'm thinking the following:
Find an expected link span
Check whether the immediate next element is also a span with the same class
and then check whether the immediate next element is also...,
and then check...
if none is found, combine the innerHtml of each span into a single anchor tag
How could I achieve such a loop?
Thanks.
There is the + selector which selects consecutive elements: http://jsfiddle.net/NWWYC/1/.
$(".RapidLink1-H + .RapidLink1-H").each(function() {
// move contents to previous span, remove this span afterwards
$(this).prev(".RapidLink1-H").append(
$(this).contents()
).end().remove();
});