jQuery: selector equivalent for parents() method - javascript

What I want to do is select an element by id, find one of its parents, and finally select a different child of that parent. I can already do that like this:
$('#id').parents('.class1').find('.class2');
However, I need to be able to do this using a single selector. For example:
$('#id parents .class1 .class2');
Is there an equivalent to the parents() method using just selectors?

Your question is really about CSS at this point, and parent selectors aren't available in CSS.
Based on your comment above, why not set your element to a variable?
var myEl = $('#id').parents('.class1').find('.class2');
widget(myEl);

Related

When to use the css element/class selector in javascript?

I'm currently working on the codecademy course on building an interactive website and I stumbled upon an ambiguity concerning the use of the elemement/class selection of the css elements.
javascript:
var main = function() {
$('.article').click(function() {
$('.article').removeClass('current');
$('.description').hide();
$(this).addClass('current');
$(this).children('.description').show();
});
};
css:
.current .item {
background: rgba(206,220,206,.9);
}
Why do I have to use the element selector 'current' instead of the class selector '.current' in line 4? Is there any rule behind it or just a specification of jquery?
Simply because the name of the class is current not .current, and in
$('.article').removeClass('current');
current is not any selector but just a classname which you want to remove, instead the selector is .article.
You are thinking that we are using element selector instead of class selector. But you are wrong. Do you see the word Class in removeClass and addClass ? It means you are passing class selector, not element selector as an argument.
Now you may ask why don't you see dot with current? Because classes are specified using dot. Actually we have already specified that we are passing Class Selector, as you can see word "Class" in removeClass and addClass .
as per docs addClass():
Adds the specified class(es) to each of the set of matched elements.
Hence, you need to pass the classname/names as parameter and not class selector built out of it.
In addClass/removeClass you use a class name (like the one you'd specify in the class attribute of your html), not a DOM selector like in $().
The function name removeClass() implies you have to state a class name. Using a selector you have to specify either you want to select a class or an ID.
The addClass and removeClass methods accept one or more space-separated classes to be removed from the class attribute of each matched element. The name of the calss you want to add/remove is "current", not ".current"
http://api.jquery.com/removeclass/
http://api.jquery.com/addclass/
In line 4, you are not using 'current' as a selector, it is a class name. Whenever you use some class name as a selector( for example in .find('.current'), $('.current') , closest('.current') etc) then only the rule of putting.for class name#` for id etc are used. And whenever you are checking some class exists( .hasClass()), adding and removing a class(addClass('current'), removeClass('current'),then you have to mention correct class name. I hope it helps.

Is it possible to select $(this) AND use selectors in jQuery

I'm wondering if I can use $(this) as well as a class selector before running a function on them.
So rather than doing;
$(this).toggleClass('open');
$('.closed').toggleClass('open');
Do something more like;
$(this, '.closed').toggleClass('open');
Whereas really, the above will select 'this' within the context of '.closed'
Regards,
You can use add():
$(".closed").add(this).toggleClass("open");
It will add this element to the set of matched elements (i.e. .closed).

How can I select an element by id and class in javascript?

I want to know if we can select an element by using its id and class at the same time. I know in css we can do that with #x.y, but but how can it be accomplished in javascript? I tried the following code and it worked fine but then all the controls with ui-slider-handle class got affected(which is obvious). I think I need a combination of id and class both so that only that particular element will be affected.
Javascript:
$(".ui-slider-handle").text(ui.value);
A combination of ID and class for selecting elements is useless as IDs are meant to be unique.
never have multiple identifiers with the same value in one page!
If you want multiple elements with the same attributes, use a class. If not, consider an ID or a class.
If you want to have a lot of elements with the same attributes, but one with extra attributes, you can give that one an ID and assign extra attributes to the ID
You will never need to do this since the ID is unique; if you know it, you can already identify the element.
Your problem is actually that your selector matches too many elements. There are other ways to limit the "range" of a selector:
Add a parent element with a certain ID/class: .parent .ui-slider-handle matches only elements with the class ui-slider-handle that are children of all elements with the class parent
You can also limit by parent type: div .ui-slider-handle
Or only direct children: div > .ui-slider-handle
See jQuery selectors for all the goodies.
Since ids should be unique, you should be able to do your selector by only id. If are wanting to apply the same attribute to multiple elements, then you should use a class. In your scenario it seems you should be fine with just using id like this:
$("#id").text(ui.value);
What you can write is:
$("#ID.ui-slider-handle").text(ui.value);
The string inside the quotes is a normal CSS selector, which supports both classes and ids. However, the above code is redundant and slow, and unless you want to select that particular id only if it has a certain class, it would be preferable to write:
$("#ID").text(ui.value);

"All but not" jQuery selector

I can select (using jQuery) all the divs in a HTML markup as follows:
$('div')
But I want to exclude a particular div (say having id="myid") from the above selection.
How can I do this using Jquery functions?
Simple:
$('div').not('#myid');
Using .not() will remove elements matched by the selector given to it from the set returned by $('div').
You can also use the :not() selector:
$('div:not(#myid)');
Both selectors do the same thing, however :not() is faster, presumably because jQuery's selector engine Sizzle can optimise it into a native .querySelectorAll() call.
var els = toArray(document.getElementsByTagName("div"));
els.splice(els.indexOf(document.getElementById("someId"), 1);
You could just do it the old fashioned way. No need for jQuery with something so simple.
Pro tips:
A set of dom elements is just an array, so use your favourite toArray method on a NodeList.
Adding elements to a set is just
set.push.apply(set, arrOfElements);
Removing an element from a set is
set.splice(set.indexOf(el), 1)
You can't easily remove multiple elements at once :(
$("div:not(#myid)")
[doc]
or
$("div").not("#myid")
[doc]
are main ways to select all but one id
You can see demo here
var elements = $('div').not('#myid');
This will include all the divs except the one with id 'myid'
$('div:not(#myid)');
this is what you need i think.
That should do it:
$('div:not("#myid")')
You use the .not property of the jQuery library:
$('div').not('#myDiv').css('background-color', '#000000');
See it in action here. The div #myDiv will be white.

Using jQuery to delete all elements with a given id

I have a form with several spans with id="myid". I'd like to be able to remove all elements with this id from the DOM, and I think jQuery is the best way to do it. I figured out how to use the $.remove() method to remove one instance of this id, by simply doing:
$('#myid').remove()
but of course that only removes the first instance of myid. How do I iterate over ALL instances of myid and remove them all? I thought the jQuery $.each() method might be the way, but I can't figure out the syntax to iterate over all instances of myid and remove them all.
If there's a clean way to do this with regular JS (not using jQuery) I'm open to that too. Maybe the problem is that id's are supposed to be unique (i.e. you're not supposed to have multiple elements with id="myid")?
.remove() should remove all of them. I think the problem is that you're using an ID. There's only supposed to be one HTML element with a particular ID on the page, so jQuery is optimizing and not searching for them all. Use a class instead.
All your elements should have a unique IDs, so there should not be more than one element with #myid
An "id" is a unique identifier. Each time this attribute is used in a document it must have a different value. If you are using this attribute as a hook for style sheets it may be more appropriate to use classes (which group elements) than id (which are used to identify exactly one element).
Neverthless, try this:
$("span[id=myid]").remove();
id of DOM element shout be unique. Use class instead (<span class='myclass'>).
To remove all span with this class:
$('.myclass').remove()
if you want to remove all elements with matching ID parts, for example:
<span id='myID_123'>
<span id='myID_456'>
<span id='myID_789'>
try this:
$("span[id*=myID]").remove();
don't forget the '*' - this will remove them all at once - cheers
Working Demo
The cleanest way to do it is by using html5 selectors api, specifically querySelectorAll().
var contentToRemove = document.querySelectorAll("#myid");
$(contentToRemove).remove();
The querySelectorAll() function returns an array of dom elements matching a specific id. Once you have assigned the returned array to a var, then you can pass it as an argument to jquery remove().
You should be using a class for multiple elements as an id is meant to be only a single element. To answer your question on the .each() syntax though, this is what it would look like:
$('#myID').each(function() {
$(this).remove();
});
Official jQuery documentation here.
As already said, only one element can have a specific ID. Use classes instead. Here is jQuery-free version to remove the nodes:
var form = document.getElementById('your-form-id');
var spans = form.getElementsByTagName('span');
for(var i = spans.length; i--;) {
var span = spans[i];
if(span.className.match(/\btheclass\b/)) {
span.parentNode.removeChild(span);
}
}
getElementsByTagName is the most cross-browser-compatible method that can be used here. getElementsByClassName would be much better, but is not supported by Internet Explorer <= IE 8.
Working Demo

Categories