What is the difference between the selectors #id and [id$='id']? - javascript

What is the difference between two statements:
$("span[id$='id']").text(var);
// And
$("#id").text(var);
HTML code is : <span class="normal11" id="id"></span>

The first one is using ends with selector while the second one is using just normal id selector.
Attribute Ends With Selector [name$="value"]
ID Selector ("#id")

By the documentation on JQuery:
$("#id") uses the JavaScript function document.getElementById(), which is extremely efficient. Link.
So, the second way should be faster and should be used.

Some different between id selector and attribute selector is
Since id selector called document.getElementById(),
it only return the first element that have a id equal to that.
However, if you use attribute selector, it will return all elements that have the id attribute that equals to that.
But duplicated id is actually invalid in HTML, and should never used.
if you really want to do that, use class instead.
example
$("#id-selector").click(function(){
$("#test").css("color", "red");
});
$("#attr-selector").click(function(){
$("*[id=test]").css("color", "blue");
});
http://jsfiddle.net/toucyqas/1/

Related

How to assign to an HTML element without knowing id/class/tag in javascript?

I'm not talking about jquery at all, but with jquery, it's easy to work with object. Like this:
$(selector)
So, selector can be: a string (can contain id, class name, tag name, attribute...) or an object. I called it: wrap the selector by $().
Can I do same thing with javascript (document.get(selector))?
I've made a function which accepts an HTML object. I want to change the style of it.
Html:
<div></div>
Script:
var changeCSS = function (selector) {
// I DON'T WANT TO USE jQuery HERE
// these function doesn't work to target the object (I'd tried)
// because I'm not sure the selector has an id, class name... or not
// document.getElementById
// document.getElementsByClassName
// document.getElementsByName
// document.getElementsByTagName
// document.querySelector
// my goal looks like: (wrap the selector by 'get' function)
selector = document.get(selector);
selector.style.width = '100px';
selector.style.height = '100px';
};
let selector = $('div')[0]; // not contain id, class name...
changeCSS(selector);
In my project, changeCSS is a plugin, it doesn't require jquery before using. But I've used jquery in another place.
Totally, I want to know how can I convert (an HTML object, not a string)
<div></div>
to a selector?
Thank you!
The querySelector and querySelectorAll methods accept a string containing a selector and return an Element or non-live NodeList respectively.
You can call them on document or an element object.
jQuery selectors allow you to select and manipulate HTML element(s).
jQuery selectors are used to "find" (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.
If you are trying to replicate the selector functionality of jQuery:
document.querySelector(.class or tag or #id);

different result with jquery and javascript

I have a select with id: param0.typeParameter.
I try to get it with jquery with:
$('#param0.typeParameter');
i get nothing but if it use this
document.getElementById('param0.typeParameter');
that work
To make jQuery select element with ID param0.typeParameter instead of element with ID param0 and class name typeParameter you should use the following:
$('#param0\\.typeParameter');
Official Proof
To use any of the meta-characters ( such as
!"#$%&'()*+,./:;<=>?#[\]^``{|}~ ) as a literal part of a name, it must
be escaped with with two backslashes: \\. For example, an element with
id="foo.bar", can use the selector $("#foo\\.bar").
SOURCE: http://api.jquery.com/category/selectors/
DEMO: http://jsfiddle.net/LtRxg/
You can try this instead:
$('[id="param0.typeParameter"]');
Or else the code assumes you want to select an element with id param0 and class typeParameter
jQuery uses the CSS-selector language. Which causes "#param0.typeParameter" to be interpretted as an element with id param0 and class typeParameter.
The jQuery statement is more similar to:
document.querySelector("#param0.typeParameter");

Selector passing to jQuery function

I have a function in which I want the selector that I am passing to do the enclosed processes. The functions are listed below:
function menuselector (id){
$(id).css('background', 'url(../img/black_denim.png) repeat');
$(id).css('color', '#FFF');
}
function menudeselector (id){
$(id).css('background', 'none');
$(id).css('color', '#CE0101');
}
menuselector('mgi');
mgi is an ID of a div tag
Ids are targeted by using a hash before the id, the same as in CSS.
If you're passing
menuselector('mgi');
You will need to adjust it to make it a valid selector.
$('#' + id).css(...
or you can send the valid selector
menuselector('#mgi');
assuming you have an element with that id (you haven't shown that)
<div id="mgi">
Aside
You shouldn't keep selecting the element. You can either chain
$(id).css('background', 'none').css('color', '#CE0101');
// on new lines for readability if there are a lot of actions
$(id).css('background', 'none')
.css('color', '#CE0101');
or use an object
$(id).css({background: 'none', color: '#CE0101'});
mgi is not a valid selector. You should write:
menusector('#mgi');
or
menuselector('.mgi');
depending on whether you want to select an ID or a class.
You could use popnoodle's solution, if your function should only be applicable to IDs, although making it restrictive like that seems like poor generality.
Just pass '#mgi' if it is an ID:
menuselector('#mgi');

jQuery opposite of "starts with" selector: [^=]

I have some div tag below:
<div class="magazine"></div>
<div class="newsletter"></div> // I need to take this div
<div class="may-moon"></div>
If I needed div with class start with "ma", I would use $('div[class^="ma"]'), but what is opposite? thanks.
The opposite would be to use jQuery :not():
$('div:not([class^="ma"])')
You can use the negative filtering function "not" like this: $('div').not('[class^="ma"]'), or the negative selector ":not" like this: $('div:not([class^="ma"])') (as pointed by Karl-André Gagnon)
You need to use :not() Selector for this. because there is no exact opposite selector exist of [^=] and * in jquery.
:not() Selector - Selects all elements that do not match the given selector.
See more about Jquery selectors
There a opposite selector exist ! -
Attribute Not Equal Selector [name!="value"] - Select elements that either don’t have the specified attribute, or do have the specified attribute but not with a certain value.
but use of this ! selector, you need to provide full-name of class.
$('div[class!="magazine"][class!="may-moon"]')
Try This

jquery hasClass, can it be given the beginning of class name, to get the full class name

I'm trying to do something similar to this question, but it's a bit different, so the solution there isn't working for me.
<span class="a-class another-class test-top-left"></span>
I have an element (this code shows a span but it could be div span or anything). This element has a class beginning with test- (test-top-left, test-top-right etc.) I've triggered a click event on classes starting with test- and saved the clicked object as var object = this;. Simple stuff so far.
What I'm trying to do now is get the full name of that class (test-top-left). I know it starts with test- but what's the full name. The thing is that there are other classes a-class another-class and test-top-left. Can hasClass be used to get the full name of the class? I'd prefer not to use find() or filter() just because there may be additional elements within that also have class="test-"
Edit:
The code I have now is, but it gives me ALL the classes. What I need is the single class beginning with test-.
var object = this;
$(object).attr('class');
So now I for loop through all the classes and test each one separately, which seems like a lot of unnecessary code. I'm hoping jQuery has a clever way to get the exact class that was clicked right away.
Description
You can use jQuerys Attribute Contains Selector, .attr() and .click() method.
Attribute Contains Selector - Selects elements that have the specified attribute with a value containing the a given substring.
.attr() - Get the value of an attribute for the first element in the set of matched elements.
.click() - Bind an event handler to the "click" JavaScript event, or trigger that event on an element.
Sample
html
<span class="anyclass test-hello">Hello World</span>​
jQuery
$("[class*='test']").click(function() {
var object = $(this);
alert(object.attr("class").match(/(test-.*?)(?:\s+|$)/)[1])
;});
Check out the updated jsFiddle
Update
If you dont want to use regex you can do this.
$("[class*='test']").click(function() {
var object = $(this);
alert("test-" + object.attr("class").split("test-")[1].split("-"))
;});
​
More Information
jQuery - Attribute Contains Selector
jQuery - .attr()
jQuery - .click()
jsFiddle Demonstration
This should work for you:
var object = this;
var className = object.className.match(/(test-.*?)(?:\s+|$)/)[1];
Class name is the name of the class you are looking for.
If you don't want to use split or regex, you can try having the class in a separate attribute
<span class="someclass test-something" _rel="test-something">test<span>
or
<span class="someclass" _rel="test-something">test<span>
with the script
$("[_rel*='test-']").click(....
And to retrieve the attribute, use $(this).attr("_rel")

Categories

Resources