I'm just wondering how I can select elements in jQuery dynamically, for example here is a selector of mine:
$("#video_background_video_0, #video_background_video_1, #video_background_video_2, #video_background_video_3, #video_background_video_4").remove();
As you can see this isn't the best example of DRY programming, I'd like to create a selector that selects all elements that begin with #video_background_video_. I basically just want to select the above elements in the cleanest way, I was wondering if there is a way that I can dynamically select these elements with some sort of count instead of placing all of my selectors like so, it just looks very messy and I'm wondering if there is a better way to do this when it comes to elements with a numeric ending?
As jQuery uses a CSS selector syntax I am unsure how I can do this.
Thanks, Nick
You can use start-with selectors:
$('[id^="video_background_video"]').remove();
There are other attribute selectors you might be interested here.
Try to use attribute starts with selector,
$("[id^='video_background_video'")
Also make sure that, this selector is not a native css based one. It will fetch the elements after executing regular expressions internally. So it would be better to use it in a minimum level. Its Better to set a common class to those elements and use class selector instead.
Related
Is there way to write data attributes in class-like form? I mean like this:
<div data-el="asset assets.asset">Some div</div>
And I want to use it like classes in selector, I need to find this element as "[data-el='asset']" and also as "[data-el='assets.asset']".
Maybe there is similar way to do so. Thanks for advices!
Take a look at the attribute selectors available:
https://developer.mozilla.org/en-US/docs/Web/CSS/Attribute_selectors
What you want to use is this:
[data-el~="assets.asset"]
That will find "assets.asset" as a single word with whitespace delimiting. I use this sort of selection sometimes and it works well.
I want to toggle(hide/show) an element when a button is being pressed. I have two ways as to implement this:
Find the element according to its class name, e.g $('.my-content')
Find the element according to its relevant DOM position towards the button, e.g. $('#my-button').parent().next().next().next()
However, none of the above seems to me very reliable since in case someone changes the HTML code, the above approaches should not work. Is there something more reliable I am missing?
If it's a specific element, supply it with an Id value and use that
to find it.
If it's a TYPE of element, use a class name.
Other than that, there's no real conventions. Just try and make sure that somebody reading your code understands what is going on.
A very good practice is to decouple HTML, CSS and JS.
When binding javascript to DOM elements you should use javascript selectors.
Basically classes with some custom prefix (like js-) which will be used only for javascript purposes (not css style).
So whenever the DOM tree structure or the CSS class names are changed, you can still have your working JS selector
HTML
<div class="my-content js-toggle-element"></div>
JS
$('.js-toggle-element')
CSS
.my-content{ ... }
Plus, using Javascript Selectors:
makes HTML highly readable: you can easily find out what will happen to that element with that js class
allows you to easily apply/disapply that behaviour also to other elements in the future, simply by adding/removing that class in your HTML and without affecting CSS at all
<div class="my-content js-toggle-element"></div>
...
<div class="another-content-to-toggle js-toggle-element"></div>
Using jQuery will be much easiest way. Like this -
$( ".target" ).toggle();
The matched elements will be revealed or hidden immediately, with no animation, by changing the CSS display property. If the element is initially displayed, it will be hidden; if hidden, it will be shown.
Reference - jQuery Toggle
If the class or the position of the element in DOM is changing then you can try
selecting it with the inner text
$("button:contains('buttontextgoeshere')")
Firstly, I do know that it is against best practice for multiple elements to have the same ID in a single page. However in this case I need for there to be two selects with the same id.
I have seen some success using this method:
$('#undo_redo_to option').length;
$('#undo_redo_to:eq(0) option').length;
*$('#undo_redo_to:eq(1) option').length;*
However, the code enclosed in *'s does not give me the proper length.
Please see the following pen, where I have created my selects and did my debugging.
LINK TO CODE
Thanks!
The problem is that jQuery uses the native JS functions first, so when you do a $('#this_id') you are effectively calling document.getElementById('this_id'). it's not just against best practice, it actually won't work... you could loop through your selects and check the id:
$('select option').each(function(){
if($(this).closest('select').attr('id')=='my_id'){
//do something
}
});
Assuming you've inherited the HTML and cannot change the ids to classes:
Note that eq() is a jQuery selector. If you change it to nth-child(2), you'll be using a CSS selector. That gives you what you need:
$('#undo_redo_to:nth-child(2) option').length;
http://codepen.io/anon/pen/WwERGW?editors=1011
You can do it with native javascript, like this:
document.querySelectorAll("[id=undo_redo_to]")
You can do it with jquery like this:
$("[id=undo_redo_to]")
This is the property selector, as the #-type selector will stop searching when the first element having that id was found.
So you can do this using plain javascript or jquery, but don't do it, because id should be unique and if it is not unique, then the HTML is invalid and it is bad for SEO.
For example, I have data-min-checkbox and data-min-select attributes.
How can I select both elements matching data-min with construction like $([data-min-*])?
Use
document.querySelectorAll("[data-min-checkbox],[data-min-select]")
Think CSS selectors for the win
i was wondering things...
If i need to get the content or append an click function to an div, as the structure of the selectors it's something like that:
$('body #content #sidebar .modalwindow #global-content')
i want to target #global-content, the final id of the selectors.
what its better?
Just target it as $('#global-content') and do what i wanna or give to it all the path?
$('#global-content') is the best selector to use, altough maybe the whole selector will be executed the same way (if jQuery starts from right to left, which I'm not sure it does). ID should be unique and getElementById() is the fastest native browser method, so $('#global-content') is the fastest possible selector.
Keep in mind also, that when you are searching for something exactly 1 level lower in the DOM tree, you can put > in the selector. Example:
$('body .content') is equialent to $('body').find('.content')
$('body > .content') is equialent to $('body').children('.content')
The second one is faster.
You can experiment and try out your selectors here
a similar question was asked in
jQuery Selectors, efficiency
the answer is that
$('#global-content')
is faster
if you know the id of your element and if your id is really unique (as it should be). It is faster to call directly the id >> $('#global-content').
Thus, it is interpreted by jquery to one of the fastest selector getElementById() instead of filtering the DOM.
Note: I know jquery 1.5 and higher (maybe even since 1.4) were optimized to select by id even if the jquery code was adding too much information but that's not the best way to rely on the framework to correct a bad coding