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() + '" />');
});
Related
I have a function:
function factCheck(index) {
if (arrayOfSites[index].indexOf("pdf") > -1) {
$('#20').attr('style', 'color: red');
$('#' + index).attr('style', 'color: red');
console.log('index: ' + index);
console.log($("#" + index).text());
}
}
So my question is. The text color of the element changes color when I use $('#20') but when I use, $('#' + index) it doesn't work.
Funny thing is, I with console.log.. it logs the text of the element but I can't effect the css of it.
Why is this happening?
// after a three hour meeting.. I came back with some really great answers!! Thank you!!
edit:
the code below shows how I'm snagging all the links on the page and add the id equal to the index of that item. So that's why I'm trying to grab that link, and effect it in some way. I appreciate all you guys.. I think I'm going to take the string and add a letter to it as they come in through the function and then manipulate the anchor from that point. I just wonder if there's a more efficient way of doing this.
$(".lpage a").each(function (index) {
// console.log(index + ": " + $(this).text());
str = $(this).attr('href');
arrayOfSites.push(str);
str = arrayOfSites[index];
title = $(this).attr('title');
parseURL(str);
$('.colContent2').append(cellOpen + '<a onclick="whichFunction(' + index + ');" id= "' + index + '"style="cursor:pointer;" class="injectedLinkCol2" >' + str + '</a>' + cellClose).prop("id", index);
});
Maybe it has something to do with the name of your id attribute. Take a look at this answer.
Try to use the toString() function:
function factCheck(index) {
if (arrayOfSites[index].indexOf("pdf") > -1) {
$('#20').attr('style', 'color: red');
$('#' + index.toString()).attr('style', 'color: red');
console.log('index: ' + index);
console.log($( "#" + index.toString() ).text());
}
}
An id name or class name must begin with a name must begin with an underscore (_), a hyphen (-), or a letter(a–z).
So something like
'#d20'
would work.
See this: Valid CSS Selectors.
I couldn't reproduce the exact problem. I made a pen (link) and tried what you asked but it works well. So it must be some error in the remaining code.
on a related note
In CSS id's are not allowed to start with a number(classes are allowed). So writing something like
#20{
color: red;
}
won't work, but the rule only applies to css. JQuery will still work, which means your only option's are to write inline styles or use JQuery's .attr or .css, but jQuery.attr() will reset all your inline styles. you are left with using .css(). So, it's better to not start your id's with numbers.
try using .css instead of .attr and see if it works.
$('.exampleClass:eq(' + index + ')').css("color", "yellow");
for some reason works
$('.exampleClas').eq(index).css("color", "yellow");
does not work.
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'm emptying a UL using jquery then I'm trying to add a new <li> after that however it's not adding the <li>
$('#pre-list').empty(); //Remove prelist
$("#pre-list ol").append('<li>' + $('#lstBox1').val() + '</li>');
Any idea why?
You are trying to select an element that does not exist (ol). You probably meant to do this:
$('#pre-list ol').empty(); //Remove prelist
$("#pre-list ol").append('<li>' + $('#lstBox1').val() + '</li>');
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();
});
I want to use Javascript to loop through a set of elements, and create a list of labels for each one, so if the set of elements were as follows:
<h1>Title</h1>
<h2>Subheading</h2>
<p>Paragraph of text...</p>
It would give me the following:
<ol>
<li>h1</li>
<li>h2</li>
<li>p</p>
<ol>
Is it possible for jQuery/Javascript to return an element's type as a string, and if so how would I go about it?
This is far from the cleanest piece of code I've ever done, but it works:
function generateList(rootElement) {
var rootElementItem = $("<li>" + rootElement.get(0).tagName + "</li>");
if (rootElement.children().size() > 0) {
var list = $("<ol />");
rootElement.children().each(function() {
list.append(generateList($(this)));
});
rootElementItem.append(list);
}
return rootElementItem;
}
var listOfElements = generateList($("body"));
$("body").append($("<ol/>").append(listOfElements));
Demo: http://jsfiddle.net/jonathon/JvQKz/
It builds upon the this.tagName answer that was previously given, but it checks for children also. This way it will build up a hierarchical view of the element given. The method doesn't generate the enclosing <ol/> tag so that it can just be appended to an existing one.
I hope this simple solution helps:
http://jsfiddle.net/neopreneur/n7xJC/
-html-
<h1>Title</h1>
<h2>Subheading</h2>
<p>Paragraph of text...</p>
-js-
$(function(){
$('body *').each(function(){
// append a 'ol' to body in order to output all tag names
if(!$(this).parents('body').find('ol').length){
$('body').append('<ol/>');
}
// output the name of the tag (list item)
$('ol').append('<li>' + this.tagName.toLowerCase() + '</li>');
});
});
This works assuming you have a properly formed HTML document with a body tag.
example
$('<ol />').append(function(index, html){
var ret = $('<span />');
$('body>*').each(function(i, el) {
ret.append( $('<li />').html(this.tagName.toLowerCase()) );
});
return ret.html();
}).appendTo('body');