multiple selectors not seems to work - javascript

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

Related

Why does jQuery return more than one element when selecting by type and ID? [duplicate]

I fetch data from Google's AdWords website which has multiple elements with the same id.
Could you please explain why the following 3 queries doesn't result with the same answer (2)?
Live Demo
HTML:
<div>
<span id="a">1</span>
<span id="a">2</span>
<span>3</span>
</div>
JS:
$(function() {
var w = $("div");
console.log($("#a").length); // 1 - Why?
console.log($("body #a").length); // 2
console.log($("#a", w).length); // 2
});
Having 2 elements with the same ID is not valid html according to the W3C specification.
When your CSS selector only has an ID selector (and is not used on a specific context), jQuery uses the native document.getElementById method, which returns only the first element with that ID.
However, in the other two instances, jQuery relies on the Sizzle selector engine (or querySelectorAll, if available), which apparently selects both elements. Results may vary on a per browser basis.
However, you should never have two elements on the same page with the same ID. If you need it for your CSS, use a class instead.
If you absolutely must select by duplicate ID, use an attribute selector:
$('[id="a"]');
Take a look at the fiddle: http://jsfiddle.net/P2j3f/2/
Note: if possible, you should qualify that selector with a type selector, like this:
$('span[id="a"]');
The reason for this is because a type selector is much more efficient than an attribute selector. If you qualify your attribute selector with a type selector, jQuery will first use the type selector to find the elements of that type, and then only run the attribute selector on those elements. This is simply much more efficient.
There should only be one element with a given id. If you're stuck with that situation, see the 2nd half of my answer for options.
How a browser behaves when you have multiple elements with the same id (illegal HTML) is not defined by specification. You could test all the browsers and find out how they behave, but it's unwise to use this configuration or rely on any particular behavior.
Use classes if you want multiple objects to have the same identifier.
<div>
<span class="a">1</span>
<span class="a">2</span>
<span>3</span>
</div>
$(function() {
var w = $("div");
console.log($(".a").length); // 2
console.log($("body .a").length); // 2
console.log($(".a", w).length); // 2
});
If you want to reliably look at elements with IDs that are the same because you can't fix the document, then you will have to do your own iteration as you cannot rely on any of the built in DOM functions.
You could do so like this:
function findMultiID(id) {
var results = [];
var children = $("div").get(0).children;
for (var i = 0; i < children.length; i++) {
if (children[i].id == id) {
results.push(children[i]);
}
}
return(results);
}
Or, using jQuery:
$("div *").filter(function() {return(this.id == "a");});
jQuery working example: http://jsfiddle.net/jfriend00/XY2tX/.
As to Why you get different results, that would have to do with the internal implementation of whatever piece of code was carrying out the actual selector operation. In jQuery, you could study the code to find out what any given version was doing, but since this is illegal HTML, there is no guarantee that it will stay the same over time. From what I've seen in jQuery, it first checks to see if the selector is a simple id like #a and if so, just used document.getElementById("a"). If the selector is more complex than that and querySelectorAll() exists, jQuery will often pass the selector off to the built in browser function which will have an implementation specific to that browser. If querySelectorAll() does not exist, then it will use the Sizzle selector engine to manually find the selector which will have it's own implementation. So, you can have at least three different implementations all in the same browser family depending upon the exact selector and how new the browser is. Then, individual browsers will all have their own querySelectorAll() implementations. If you want to reliably deal with this situation, you will probably have to use your own iteration code as I've illustrated above.
jQuery's id selector only returns one result. The descendant and multiple selectors in the second and third statements are designed to select multiple elements. It's similar to:
Statement 1
var length = document.getElementById('a').length;
...Yields one result.
Statement 2
var length = 0;
for (i=0; i<document.body.childNodes.length; i++) {
if (document.body.childNodes.item(i).id == 'a') {
length++;
}
}
...Yields two results.
Statement 3
var length = document.getElementById('a').length + document.getElementsByTagName('div').length;
...Also yields two results.
What we do to get the elements we need when we have a stupid page that has more than one element with same ID? If we use '#duplicatedId' we get the first element only. To achieve selecting the other elements you can do something like this:
$("[id=duplicatedId]")
You will get a collection with all elements with id=duplicatedId.
From the id Selector jQuery page:
Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.
Naughty Google. But they don't even close their <html> and <body> tags I hear. The question is though, why Misha's 2nd and 3rd queries return 2 and not 1 as well.
If you have multiple elements with same id or same name, just assign same class to those multiple elements and access them by index & perform your required operation.
<div>
<span id="a" class="demo">1</span>
<span id="a" class="demo">2</span>
<span>3</span>
</div>
JQ:
$($(".demo")[0]).val("First span");
$($(".demo")[1]).val("Second span");
Access individual item
<div id='a' data-options='{"url","www.google.com"}'>Google</div>
<div id='a' data-options='{"url","www.facebook.com"}'>Facebook</div>
<div id='a' data-options='{"url","www.twitter.com"}'>Twitter</div>
$( "div[id='a']" ).on('click', function() {
$(location).attr('href', $(this).data('options').url);
});
you can simply write $('span#a').length to get the length.
Here is the Solution for your code:
console.log($('span#a').length);
try JSfiddle:
https://jsfiddle.net/vickyfor2007/wcc0ab5g/2/

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

Add class to li if content is a certain string

Would it be possible to add a certain class to a li that contains a certain string of text using JavaScript/jQuery?
UPDATE/NEW QUESTION:
Instead of detecting the content of the li, can I have it add the class if the li has another specified class?
Answering the fellow's extended question:
$('li.yourClass').addClass('anotherClass');
You're asking really basic questions. I'd recommend you just spend some time with the beginner jQuery tutorials on the site and you'll understand all of this stuff much better.
Edit: IGNORE MY OLD ANSWER. You learn something every day. Do this, not what I said:
//http://api.jquery.com/contains-selector/
$('li:contains('+ searchText +')').addClass('myClass');
Old answer:
$('li').each(function(){
var _this = $(this);
if( _this.text() === testString ){
_this.addClass('myClass');
}
});
In the if statement, you can change that to check the .html() of your li or even do a more advanced regex if you need that. But basically, you have to loop through the li's in one form or another to check their content against your testString.
$('li').filter(function () {
return $(this).text().indexOf('certain string') !== -1;
}).addClass('certainClass');
You can use the jQuery filter function.
The filter function can be passed a selector instead of a function:
$('li').filter('.specified-class').addClass('certainClass');
at which point you should probably just update the initial selector:
$('li.specified-class').addClass('certainClass');

Find prev() tags with several selectors

Let's face this situation:
<ul>
<li>data</li>
<li class="selector">data2</li>
<li class="selector2">data3</li>
</ul>
What i'm trying to do is match lis that either have selector class or have class attribute undefined, something like this:
jQuery(function($) {
$('.selector2').prevAll('li.selector OR li[class==""]');
});
So if I'm running prevAll() on the .selector2, it should return 2 list items. If i run it on .selector, it should return the first list item.
So is there a way to replace that OR ... ?
PS: xpath may work for me too as i'm developing for modern browsers
jQuery(function($) {
$('.selector2').prevAll('li.selector, li:not([class])');
});
DEMO
Adding in important comment from #pimvdb
This is correct, but be careful - something like
.addClass("foo").removeClass("foo") leaves the class attribute
behind, although you (might) expect it to be in it's initial state. So
it's not quite the same as [class=''].
What i'm trying to do is match lis that either have "selector" class
or have class attribute undefined
This XPath expression is equivalent to the pseudo-code in the question:
/ul/li[#class='selector2']/preceding-sibling::li[#class='selector' or not(#class)]
However, a literal translation of the quoted requirement is:
/ul/li[#class='selector' or not(#class)]

How can I use multiple Floating Help Dialogue by using 'class' instead of 'id'?

I need to use multiple floating help dialog boxes in a page. I have tried it by using 'display:block' and 'display:none' and used ID in javascript. I cannot use classes since I have multiple of them on the same page and if I use classes then all of them will be displayed/hide at the same time. However, as the number of help items are increasing in the page, I have to go back to the javascript and add more lines ...
for example:
$(document).ready(function() {
$("#help-icon1").click(function() {
$('#help-details1').css('display', 'block');
});
$("#help-icon2").click(function() {
$('#help-details2').css('display', 'block');
});
$("#help-icon3").click(function() {
$('#help-details3').css('display', 'block');
});
});
Each of them also have close icons and they should be disappeared if clicked on that close icon or clicked anywhere in the page. That means I have to write javascript functions 3 times for all the different close icons.
I tried to rely on jquery's "next" feature, but since there are many layers (div/p/span) in between the areas where the help icon is places and the help text, it becomes problamatic. Any idea or any better way to resolve this?
Thanks in advance.
I'm not quite sure I understand what you are looking for, but you can set up all the click handlers in one step, and have each one refer to itself in the handler:
jQuery(".help-icon").click(function() {
jQuery(this).css('display', 'block');
});
You can add additional class names to an element.
A div can be hidden by default, and a new class can be appended to it - to "overrule" the previous style (Hence the name Cascading Style Sheets)
<div class="hidden exception"></div>
If an element is clicked, you can append a new classname like so:
$('.target').addClass('newclass');
more info:
http://api.jquery.com/addClass/
I've not done it using JQuery but what you need is "unobtrusive javascript".
It does get done by using a class. Say you have images you all want highlighted:
<img src="pic1.png" onMouseover="this.src='hi_pic1.png';" />
so they all have the same behaviour. Give them a class:
<img src="pic1.png" class="hi" />
Then at load time, on in the script at the end of your page, yahoo-style, you write an initialisation to
- grab every element of the class
- add the event(s) you want
- set the event to use the appropriate data, e.g. by using this and by using systematic names like pic1 -> hi_pic1.
Hope this helps,
Charles
Have you tried the jQuery .each function?
EDIT: Like the following
$(".help-icon").each(function(idx, elm){
elm.click(function(){
...
})
});
If all of your help icons have the same class you can use jQuery's each function to loop through them, retrieve the associated id, replace "icon" with "detail" in the id (so #help-icon3 would become #help-detail3), and then use that to update the panel. Something like:
$(".help-icon").each(function() {
var detailsId = $(this).attr("id").replace("icon", "details");
$("#" + detailsId).css('display', 'block');
});
Let's just ASSUME that you need to use IDs for some unknown reason. Here's your answer to combine efforts:
$("#help-icon1").add("#help-icon2").add("#help-icon3").click(function() {
$(this).css('display', 'block');
});
Which equates to:
$("#help-icon1, #help-icon2, #help-icon3").click(function() {
$(this).css('display', 'block');
});
But really, you don't need to use unique IDs like this without some pretty good reasons.

Categories