How to generate dynamic id using jQuery? - javascript

I want to add progressive id to a series of elements on an unordered HTML list. I used the jQuery .each() method to get each <li> of the List and append a <span> inside each <li>. Then I added the ID attribute with index of each() as number.
$('#menu li ul li').each(function(i, e){
$(this).append('<span class="arr"></span>');
$(".arr").attr("id", "id_" + i);
});
Fiddle Demo
But I get id_3 for all elements. Why? What did I do wrong?
Thanks for any help!

It is because you are applying it to .arr globally, so overriding it every time.
You need to be more specific with adding it, by finding the .arr in you current li.
Change your code to be:
$('#menu li ul li').each(function(i, e){
$(this).append('<span class="arr"></span>');
$(this).find(".arr").attr("id", "id_" + i);
});

As has been pointed out, $(".arr") targets every element with the arr class, so on the fourth iteration you update all such elements to the id_3 id.
You can limit the selection with $(".arr", this) or $(this).find(".arr"), but it would be easier to just turn the append around:
$('#menu li ul li').each(function(i, e){
$('<span class="arr"></span>')
.attr("id", "id_" + i)
.appendTo(this);
});
That is, create the element first, set its id, then use .appendTo() instead of .append().
Or rather than calling .attr() you can pass the desired attributes directly to the $() function when you create your span:
$('#menu li ul li').each(function(i, e){
$('<span></span>', {
"class": "arr",
"id": "id_" + i
}).appendTo(this);
});

You are targeting a class when assigning the attribute. Every element you create is created with the same class so all items get assigned the same attribute. This code saves the newly created element to a variable called elem and then sets the attribute ID of that newly created element.
var elem = $(this).append('<span class="arr"></span>');
elem.attr("id", "id_" + i);

You need to scope your $(".arr").attr("id", "id_" + i); selector. Its currently pulling all the <span> tags each time. I'm guessing you have 4 total at this point, which is why they are all getting set to "id_3".
Added in $(this) to your selector.
$('#menu li ul li').each(function(i, e){
$(this).append('<span class="arr"></span>');
$(".arr", this).attr("id", "id_" + i);
});
Modified Fiddle: http://jsfiddle.net/NZgyD/2/

you can do it this way
$('#menu li ul li').each(function(i, e){
$(this).append('<span id="id_' + i + '" class="arr"></span>');
});

because $(".arr") is selector for multiple items

Related

JS OR Jquery to Add Link to List items

how would I add a link to each list item?
basically I have a list and i want to use js or jquery to added in href for my search page.
<aside class="listlinks">
<ul>
<li>CRM</li>
<li>CTI</li>
<li>Call Center</li>
<li>Data warehouse</li>
<li>Documentum D2</li>
<li>MDM</li>
<li>SharePoint</li>
</ul>
</aside>
$('.listlinks').each(function(){
$(this).wrapInner('<a href="\search.php?' + $(this).html() + '" />');
});
Your example would work as long as you updated the jQuery selector to match the list items instead of the parent list, e.g. replace .listlinks with .listlinks ul li. You should also make sure you properly encode the text in the href portion with encodeURI or encodeURIComponent.
You don't really need jQuery for this and using pure Javascript and manually concatenating would save you 3-4 function calls per list item.
$('.listlinks ul li').each(function(){
this.innerHTML = '' + this.innerHTML + '';
});
You can shorten this even more by sacrificing one function call per list item and using String.prototype.link. The link method automatically wraps string objects with a hyperlink to the supplied URL.
$('.listlinks ul li').each(function(){
this.innerHTML = this.innerHTML.link('\search.php?' + encodeURIComponent(this.innerHTML));
});
$('.listlinks ul li').each(function(){
$(this).append('<a href="\search.php?' + $(this).html() + '" />');
});
You could do
$('.listlinks ul li').each(function(){
var text = $(this).html();
$(this).html('' + text + '');
});
Update:
Make sure to encode the text in the url. Just remembered that
# Rayen Kamta try this:
$.each($('.listlinks li'),function(k,v){
$(v).wrap('<a href="\search.php?' + $(v).html() + '" />');
});

how to remove particular li from ul using javascript/jquery?

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();

target single element when it is not possible to use $(this)

function modalClosed(){
$("div#tab" + tabId).find('ul')
.prepend("<li>item</li>")
.hide()
.fadeIn('slow');
}
I want the list (<li>) to be prepended and have fade in effect one by one, unfortunately I have no way of using $(this), the above code doesn't work well, it apply effect on all of the <li>.
That's because .prepend() returns the ul element not the appended li element, so you are hiding/showing the ul element. You can reverse the logic using prependTo() method, now .hide() and .fadeIn() are applied to the appended element not the ul element.
$("<li>item</li>").hide()
.prependTo("#tab"+tabId+" ul")
.fadeIn('slow');
http://jsfiddle.net/5yj7v/
function modalClosed(num) {
$("div#tab" + tabId).find('ul')
.prepend("<li>item</li>")
.hide()
.fadeIn('slow', function() {
// callback function, called when fadeIn has finished
if(num > 1) {
modalClosed(num - 1);
}
});
}
From what I understand You want fade in effect one by one on all li items. If that is correct then try the following:
var time=1000;
$("div#tab"+tabId+" ul").prepend("<li>item</li>");
$("div#tab"+tabId+" ul li").each(function() {
$(this).hide();
$(this).fadeIn(time);
time+= 800;
});
http://jsfiddle.net/PV4dC/5/

make parent menu item bold when visiting child page

I have the following code which gives the menu item a class of 'current'. I then style that with font-weight:Bold;
$(document).ready(function () {
var loc = window.location.href;
$("ul a").each(function() {
if (loc.indexOf($(this).attr("href")) != -1) {
$(this).addClass("current");
}
});
});
If the user is on a page which is within the sub menu ul li a how do i add a class called Bold to the parent UL/LI at the root level?
here is the structure, if i am on Q&Z Group then About us needs to be bold. - http://jsfiddle.net/zZQy3/
var loc = window.location.href;
$("ul a").each(function() {
if (loc.indexOf($(this).attr("href")) != -1) {
$(this).addClass("current");
$(this).parent('li').parent('ul').addClass("Bold");
}
});
You are looking for the parent:
$(this).parent("li").parent("li").addClass("bold");
Note there are two parents above - this is because your a element is within an li, which is not what you want bold. You want the li parent of THAT to be bold.
if you have the current node as a jquery variable, you can access its parent by using parent. So, you could use $(this).parent().addClass(...);
If you wanted to, rather than using javascript for this logic, you could use the selector:
$('ul li:has(a[href=' + window.location.href + '])').addclass(...);
This is looking for any LI that has a descendant with an href matching the current url by way of the Has and Attribute Equals selectors.

Full selector string or this.find and selector string

Both work, but is there any advantage / dis-advantage of using one over the other ?
$("#" + this.id + " > ul > li.active:first")
vs
$(this).find(" > ul > li.active:first")
The second selector works, I'd go with that instead of concatenating the ID into the first selector (looks ugly) and making jQuery look for that same element ID again (redundant).
You could also do this... I think.
$(" > ul li.active:first", this);

Categories

Resources