Find one DOM node when several share the same class - javascript

I am stuck at one place in jquery, In have multiple dropdowns which is generating dynamically and have the same class name.
I am trying to trigger a click event on that class but that is affecting all of them.
What i want is just to point to the one which comes in a loop not to all
Something like this. ?
here is the jquery
if(olddate[0]==='')
{
$(".month").first().val($(".month option:first").first().trigger("change"));
}
if(olddate[1]==='')
{
$(".day").val($(".day option:first").trigger("change"));
}
if(olddate[2]==='')
{
$(".year").val($(".year option:first").trigger("change"));
}

To make the code work, you have to create "context" somehow. Context can be:
Wrap each dropdowns in an element has an ID. You can then do $('#id .month') to locate the node. See Descendant Selector
Save the root of the dropdown in a JavaScript variable. You can then do $('.class', rootNode) to locate it. See jQuery()

Related

How to get parent using $(this)

I'm trying to further my understanding of traversing and correctly using $(this).
I understand $(this) is used in reference to the context. However, say I have three items that are identical to each other (HTML-wise) and if a user clicks on an input, I want the events to not only happen for the item the user selected, but be able to access the parent element ".item" as well. This way, I can hide other elements within ".item" because, again, the context would be the "input" that the user clicked.
This is where I am confused. When a user clicks on the input ($('input').on('click', doSomething);), I am limited to the context of the input - nothing is inside the input, so I want to access other elements that are out of the input context.
I then try and use $(this) to say I only want THIS event to happen for THIS item only, not affecting ALL items.
Here is a code example: JSFIDDLE
I've tried researching this and I can't find much information on an instance like this so hopefully this could benefit others too. Feel free to make edits to the content / heading as I've tried to be as specific as possible.
To get the immediate parent(s) of the element(s) in a jQuery set: parent. (If your set has only one element, as $(this) will, that will give you that element's immediate parent.)
To find the closest element(s) to the elements(s) in a jQuery set matching a given selector, starting with the current element(s): closest. (If your set has only one element, as $(this) will, that will give you the first element matching a selector starting with that one element, then looking at its parent, then its parent, etc.)
This should be your click-handler code :
function doSomething(event) {
$(event.target).parent().find('ul').hide();
}

How to remove all instances of a class in javascript/jquery?

I have this class called .m-active that is used multiple times throughout my HTML.
Basically what I want to do is remove all instances of that class when a user clicks on an image (which does not have the m-active class) and add the m-active class to that image.
For instance in a Backgrid row you might have a click handler as follows:
"click": function () {
this.$el.addClass('m-active');
}
But you also want to remove that class from any rows to which it was previously added, so that only one row at a time has the .m-active class
Does anyone know how this can be done in javascript/jquery?
With jQuery:
$('.m-active').removeClass('m-active');
Explanation:
Calling $('.m-active') selects all elements from the document that contain class m-active
Whatever you chain after this selector gets applied to all selected elements
Chaining the call with removeClass('m-active') removes class m-active from all of the selected elements
For documentation on this specific method, see: http://api.jquery.com/removeClass/
Getting grasp of the whole selector thing with jQuery is challenging at first, but once you get it, you see everything in very different light. I encourage you to take a look into some good jQuery tutorials. I personally recommend checking out Codeacademy's jQuery track: http://www.codecademy.com/tracks/jquery
all answers point to remove the class from the DOM element. But if you are asking to remove the element itself you can user .remove() jquery method
$('.m-active').remove();
JQuery Remove Docs
In plain JavaScript (no jquery):
for (elem of document.getElementsByClassName("m-active")) {
elem.classList.remove("m-active");
}
Jquery-:
$("class").removeClass("your class");
javascript-:
Set the class name to nothing when you want to remove class in javascript!!!
document.getElementById("your id").className = "";
or
element.classList.remove("class name");
Specifically addressing the code block added to strengthen the quality of the question, and borrowing from jsalonen:
"click": function () {
$('.m-active').removeClass('m-active');
this.$el.addClass('m-active');
}

Jquery Class Selector Fails to Select new Class Instances Added with .append()

I'm semi-new to Javascript/jQuery so apologies in advanced if I'm missing something basic. I have a function that is triggered whenever a user types in an element with a specific class.
$('.relevantClass').keyup(function(){
//code...
});
Now this function may end up, depending on the situation, creating a good deal of new HTML including new instances of relevantClass through the .append() method.
var newHTML = <div class='relevantclass'>Content...</div>;
$('#wrapper').append(newHtml);
However, the jQuery selector does not seem to detect and execute the function when a user types in the newly created relevantClasses. I've checked the newly created Html and it has the correct class tags and old instances of the relevant class due work.
I'm guessing this has something to do with .append(); messing with the DOM and I need someway to "refresh" the selector and let it do its jQuery thing researching the DOM to find the new classes. Any thoughts on how to do this? Is there some jQuery method I can't find?
You have to use on() to attach events that work on dynamic content:
var $parent = $("selector"); //the element you're appending .relevantClass to
$parent.on("keyup",".relevantClass",function(){
//code...
});
Keep in mind that to work with dynamic content, you have to attach the event to relevantClass's closest parent that exists on page load.
Some people use body, but you should get used to using parent elements as close as you can get to the dynamic content. This is so that event delegation occurs on a smaller scale.
More info on on() here.
Also, I hope that newhtml variable is wrapped in quotes.
$('.relevantClass').on('keyup', function(){
//code...
});
Try something like
$('body').on('keyup', '.relevantClass', function() { ... }
The idea is that you use an existing root element and use your class selector as a filter. See the examples here.

Modifying all element in a class with js

I am trying to hide/show a class of elements in a form depending on a drop-down menu choice made by the user. See: http://jsfiddle.net/3FmHK/2/
I am new to js and have two problems, so maybe they are obvious, bear with me.
1) I am modifying by the div id, so only the first element changes (and not in this fiddle for some reason, but it does in the project). However I want all the elements of a class to modify and I haven't been able to make that work. So how do I modify the style="display" for an entire class, rather than a single element?
2) The remove does not work for newly added element, when the form is returned with values in the project, they are removable. Using firebug, the code looks identical for the GET return generated elements vs the user added elements, as far as I can tell. Why does the remove function not work for newly added elements?
I recommend using jQuery for this if you can. You can use the .on() feature to bind actions ot newly created elements and use the class selector to .hide() all classes then .show() the currently selected on by id.
It would look something like this:
jQuery(document).ready( function() {
jQuery(document).on('click', '.classname', function() {
jQuery('.' + jQuery(this).attr('class') ).hide();
jQuery(this).show();
// Or you can use the following to show a specific ID element.
//jQuery('#idtoshow').show();
)};
});
This will hide all elements with the class name. You will need to include the jQuery library before your script. Although I am only using show and hide here, you can use .remove() as long as you bind your action with .on and not just .click. You need .on to bind to newly created elements.
http://api.jquery.com/on/
Hope this helps.
Try:
$(this).parent('div').first().remove();

Rapid repeated traversing within a div

I have a number of divs, each of which contain an instance of a number of different items, each with their own unique classes and/or ids.
A lot of .js code applies to the elements within each of these parent divs, and my .js is getting bloated by the constant need to do things like:
// Stuff like this occurs 15-20 times for similar but different actions
$(this).parent().nextAll('.target').eq(0).find('.toggle').slideToggle();
$(this).next('.alert').html('Success');
In the context of the document, I see why this code is necessary. However, I feel that if I were only able to redefine the reference point as being the parent div instead of the whole document, I could replace the convoluted code above with the MUCH easier:
function keepingCodeWithinParentDiv(){
$('.toggle').slideToggle();
$('.alert').html('Success');
}
So, is there a way to say in Javascript: for this part nothing exists outside this div?
If you have a parent element (let's name it element) that you want to confine your jQuery selector operations to, you can just pass it as a context to any jQuery select:
$(".toggle", element).slideToggle();
See jQuery doc for more info.
If you show us your actual HTML and describe what you're trying to get, we could give more specific advice.

Categories

Resources