div not being selected when pound sign is appended - javascript

For debugging purposes, this is what I tried to type in Chrome Console:
$("#loading")
> null
But if I do this, it correctly retrieves the div:
$("loading")
> <div id="loading" align="center" style="display: none;">
I'm using jquery-1.4.1.min.js.
<script type="text/javascript" src="../../js/jquery-1.4.1.min.js"></script>
This doesn't make sense to me, why can I not select a div by # sign but I can when I exclude it?
Edit: Sorry, huge fail on my part. I meant the other way around. Please see the revised question.
The only other js library i have is prototype.js, which is loaded after jquery script.

$("#loading") indicates to get dom with specific id for that # sign is used.
without # jQuery will not recognize dom with id.
Similarly to get specific DOM with class name you has to use .
Some example selectors are :
Selector Example Selects
* $("*") All elements
#id $("#lastname") The element with id="lastname"
.class $(".intro") All elements with class="intro"
.class,.class $(".intro,.demo") All elements with the class "intro" or "demo"
I have checked at my side and see the result.

You should have a look at the jQuery selector documentation.
Some basic rules when using jQuery selectors follow (these are by no means exhaustive, you should look at the docs):
Using a # at the beginning of your selector will search for all DOM nodes with an id of whatever word follows the #. So $('#loading') will select DOM nodes with id="loading". This should only return one element, since non-unique ids on a page are invalid HTML.
Using a . at the beginning of your selector will do a similar search to #, but will look at all DOM nodes' class attributes instead and select those with a class matching your selector. So ('.loading') will select DOM nodes with loading in their class attribute's value.
Using simply a word with no preceding symbols will attempt to select all DOM nodes whose element tag name matches your selector's word. So $('loading') will attempt to find all <loading> tags, but since this isn't an actual HTML tag, nothing will be selected.
EDIT
So while the above is true, it seems that you had conflicts between prototype.js and jQuery. These are well known and much lamented. You can look at jQuery's wiki entry on using jQuery with other libraries and the documentation on jQuery.noConflict() for more information on this. Essentially, you will need to use jQuery instead of $ to access the jQuery library.

$("loading") indicates that you are selecting an html element tag like <div> tag ($('div')).
$("#loading") indicates that you are selecting an html element tag with id like <div id='loading'>.
Have a look at jquery selectors... http://api.jquery.com/category/selectors/

Related

I can't find any documentation on this CSS selector.. what is it?

I am using jQuery to change the width of a sidebar, and within the working code on CSS it shows this:
#wrapper.MenuDisplay #my-sidebar-wrapper {
width: 200px;
}
But after looking through w3schools and mozilla etc, I have not found any selector which looks like #foo.bar.
The reason I am trying to figure this out is that I can't understand why this CSS isn't applied straight away, and how a jQuery toggleClass is able to get this width to be applied (which it successfully does) on a button click.
Does anyone know what is going on here? What the selector is and why it works after clicking on a jQuery button but not straight away on page load?
Many thanks
That means element with id foo and class bar, shortened to #foo.bar
[id][class]
#wrapper is id of an element, and .MenuDisplay is class. Element must have that id and class to get that CSS work.
#foo.bar
matches an element that has both id = "foo" and class = "bar".
It appears you are asking what a sequence of selectors means.
According to current W3C standard, it is...
...a chain of simple selectors that are not separated by a combinator. It always begins with a type selector or a universal selector. No other type selector or universal selector is allowed in the sequence.
Not everyone considers the second sentence of the definition true, because, for example, #this or .that appear not to begin with either a type selector (a, div, span, etc...) or a universal selector (*). However, one should bear in mind that...
...whenever a sequence of selectors does not begin with a type or universal selector, it "defaults" to starting with an omissible universal selector.
So, #this is a shorthand for *#this, .that is a shorthand for *.that. And #this.that is a shorthand for *#this.that.
In fact, if you read the entire universal selector paragraph, you'll notice a note at its end recommending it not to be omitted.
However, almost nobody respects this recommendation and, in practice, the only time you'll see a universal selector is when someone wants to give a CSS property to every single element in the page.
Like in * {box-sizing: border-box;}
As a side note, not omitting the universal selector in your CSS is supposed to make it faster. This is not difficult to test and appears to be true, but the differences are negligible.
Well As far as I can understand from your question,
jQuery Selectors allow you to select and manipulate HTML element(s) or select HTML elements based on their name, id, classes, types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in addition, it has some own custom selectors.
In this case:
#foo.bar points to an element in the DOM that has an id="foo" and a class="bar".
jQuery Selector Tester to demonstrate the different selectors:
jQuery Selectors Test Page
Hope I could help!
#foo.bar refers to the element with together foo id and bar class.
$('#foo.bar').fadeOut('slow');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='foo' class='bar'>box</div>

Why does the jquery selector ("id,id") selects all elements with duplicate IDs

I came across some year old code written by a good developer (yes, I knew him personally) to access all elements having the same id.
$("#choice,#choice")
It returns all elements having the id. But if we use the below
$("#choice")
It returns only the first match, as expected.
After searching for some time, I'm unable to figure out any official links pointing to his technique, as to how it selected all elements with duplicate id.
Can anyone please explain how is this working ?
UPDATE
Please see the question is not about what alternative to use. I'm aware of classSelectors and attributeSelectors and know having duplicate IDs is not recommended, but sometimes you just have to live with years old code the way it is (if you know what I mean).
http://jsbin.com/zodeyexigo/1/edit?html,js,output
If you look at the code of sizzle.js that jQuery uses for selecting elements based on selector you will understand why this happens. It uses following regex to match simple ID, TAG or class selector:
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
but as the selector in question is $("#ID,#ID") it does not match with the selector and uses querySelectorAll (line no 270 in ref link), which replaces selector to "[id='" + nid + "'] " (line no 297 in ref link) which selects all the elements with matching ID.
However, I agree with the other people in this thread, that it is not good idea to have same ID for multiple elements.
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 tag selector, like this:
$('span[id="a"]');
Having duplicated id on the page making your html not valid . ID is unique identifier for one element on the page (spec). Using classes, that are classify similar elements that's your case and $('.choice') will return set of elements
So in JS Fiddle i have shown an example of what jQuery is doing.
https://jsfiddle.net/akp3a7La/
When you have a
$('#choice,#choice');
It is actually getting all the instances of the objects #choice twice, and then filtering out any duplicates.
in my example i show you how it does that also when you have something like this
$("#choice,li");
Where items are actually your #choice items.
In the Jquery Documentation
https://api.jquery.com/multiple-selector/
it talks about multiple Selectors, which is what i think is happening here, your developer friend is selecting the same ID twice, and it would be returning it twice. as you can only have one input with the same ID once on a page (good html syntax)

Select elements jQuery with Regex

I have a HTML page where many elements are dynamically inserted as the user requests. Each of these elements have an id attribute with some string plus a numeric id value plus another string.
Example: budget_budget_alive_elements_attributes_10_unit_value
And so I tried the following selector:
$("#budget_budget_alive_elements_attributes_\d+_unit_value");
But it unfortunately does not work.
Some person wrote an article of an extension to jQuery selector for fetching these kinds of ids but I had no luck with that, either.
Can you help me here? Given the constraints of the element's id values, how can I make a selector for them?
You'd better use class selector (by adding same class to these elements).
Else you have to use something like:
$("[id^='idbudget_budget_alive_elements_attributes']")

Is there any usage of Sizzle to get unique search results from an html document?

I am newbie in both JS and Sizzle, trying to implement a system that generates links according to a keyword like Google AdSense do. I ve searched and decided to use Sizzle CSS Selector for this.
I have an html document and a keyword, I want to search "all keywords which are not in a link ( tags).
My Sample HTML part
<div> <p>... some text ....
....................................
<strong>......keyword......</strong>
....................................
...........................keyword..
....................................
</p> </div>
I used ":contains" selector to search this keyword in JS and used document body as search context. After search results I will replace the elements with some link(keyword).
Sizzle(":contains(keyword)", document.body);
It returns me an array contains "div, p, strong" elements.
There is 2 "keyword" s in the context both it returns parent elements
of results (div is unnecessary here).
Is there any usage of Sizzle to prevent this problem?
An extra question: I searched Sizzle selectros, also w3c selectors. ":not" selector is used to get negative given selector. How can I see the element is not in a link tag without traversing dom with "parentElement" attribute(I mean with sizzle selectors considering the link tag can be upper parent nodes of element).
Thanks.

Get an element that has an ID which starts with some characters using Dojo

I have a node defined by the following HTML markup:
<div id="_13:3AVAsa7qVvAprAar19ie8LRorrLEm2g" >asdf</div>
I need to get a reference to it without using it's full id like:
dojo.byId('_13:*');
Is it possible or is there any other ways that could be achieved?
You should use the attribute starts-with selector.
I've never used Dojo, but looking here:
http://dojotoolkit.org/reference-guide/dojo/query.html
It seems that you need this:
dojo.query('div[id^="_13:"]')
That same link also contains examples of other useful selectors at the end of the page.

Categories