Full selector string or this.find and selector string - javascript

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

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 generate dynamic id using jQuery?

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

Find and replace HTML string with jQuery

Links from the database are website titles and render on the page "Interesting Article: Author" - but occasionally the link is a question "Where's China?: GoogleMaps". The ?: looks silly so I wanted to replace the HTML ?</span>: with ?</span>.
Here is the jQuery I worked out:
$('#relatedinfo ul li a').html().replace('?</span>:','?</span>');
But this doesn't actually replace it in the DOM. How do I get that string to actually change the page?
I'd suggest:
$('#relatedinfo ul li a').html(function(index,html){
return html.replace(/<\/span>(\:)/,'');
});
JS Fiddle demo.
Or even:
$('#relatedinfo ul li a').text(function(index,text){
return text.replace(':','');
});
JS Fiddle demo.
An updated approach is to check that the last character in the span is in the array of ['?','!','.'] and, if it is, then to remove the : from the nextSibling's nodeValue:
$('#relatedinfo ul li a span').text(function(index,text){
var lastchar = text.split('').pop();
if (['?','!','.'].indexOf(lastchar) > -1) {
this.nextSibling.nodeValue = this.nextSibling.nodeValue.replace(':','');
}
});
JS Fiddle demo.
References:
html().
String.replace().
text().
You can also use regex :
var rx = new RegExp('(?![^<&]+[>;])' + searchString, 'gi');
$('#relatedinfo').html(function (i, html) {
return html.replace(rx, '<b>$&</b>')
});
source : jQuery to Find/Replace html text when not inside an html tag other than P, DIV, SPAN, TD

jQuery Selector equivalent of javascript

I am trying to get the jquery equvaliant of this javascript
var id = $(this).parent().parent().parent().attr("id");
document.getElementById(id).getElementsByClassName("addcomment")[0].style.display = 'block';
but its not working
$('#+id+' '.addcomment').css('display','block');
Any suggestions ?
$('#' + id + '.addcomment').css('display','block');
as a sidenote in the page you should have only one element with that id, so
$('#' + id ).css('display','block');
should works too (of course only if classname it's not necessary to target it, since this is a different selector)
$('.addcomment', '#' + id).css('display','block');
or just simple
$('#' + id).css('display','block');
I think you need to get the child elements based on their class. So try this.
$('#' + id ).find('.addcomment').show();

Best way to GET the xpath and css selector of a specific element

Looking for the best way to GET the xpath and css selector of a specific element using jQuery or Extjs. To basically select a random element and traverse up the dom and retreive it's unique css selector or xpath. Is there a function that can do this already or does anyone have a custom function that can do this?
Why not just check for an "id" value, and if there is one there just use it. If there isn't one, generate a unique random "id" value, give it to the element, and then use that.
edit: here's a proof-of-concept jQuery hack to build up a selector for any element you click on.
$('*').unbind('click.m5').bind('click.m5', function(ev) {
if (this != ev.target) return;
var cn = function(elem) {
var n = $(elem).parent().children().index(elem);
return elem.tagName + ':nth-child(' + n + ')';
};
var selector = cn(this);
$(this).parents().each(function() {
if (/BODY|HTML/.test(this.tagName))
selector = this.tagName + '>' + selector;
else
selector = cn(this) + '>' + selector;
});
console.log("Selector: " + selector);
$(selector).css('background-color', 'red');
});
There are an infinite number of selectors for any given element. What do you need it for? You might be able to use Firefox plugin like XPather?

Categories

Resources