how to find the class name of 'deepest' div in javascript/jquery? - javascript

I am aware that e.target contains the info of the element just below the cursor, but what if I want to know the class name of the div which has a table>tr>td>button in it and I'm clicking that button inside that td. I know this events bubbles up and there should be a way to find out if the div exists in that bubbling levels. Any help.
Scenario: button is inside a modal window. How do I find the modal windows class name on click of the button inside it.

Use .closest() to traverse up the DOM to the nearest match:
var parentDiv = $(yourButton).closest('div');
Or in the button's click:
$(yourButton).click(function() {
var nearestParentDiv = $(this).closest('div');
// And read its class
console.log(nearestParentDiv.attr('class'));
});
The selector .closest() accepts can of course be more specific than this, so if if the modal window <div> has some known class but you need to inspect its other classes, you should use the more specific selector.

Yes as you say the event will bubble up to your div, so just make the div handle the event with .on() , like this:
$('#yourdiv').on('click',':button',function(e) {
alert( $(e.delegateTarget).attr('class') );//alerts the classes of #yourdiv
alert( $(this).attr('id'));//alerts the id of the clicked button (if have one)
});
UPDATE:
Fixed obtaining the reference to the original div where the event was attached. With event.delegateTarget from the Event object . Thanks Cristophe and Kevin B. for spotting the error.
See working demo

You can use .parent() to get the parent div attributes like id: http://jsbin.com/ololad/1/edit
$('button').click(function(){
console.log($(this).parent().attr('id'));
});

Related

Is there any difference beetween cloned div and a div created in loop?

Is there any difference between a div cloned and a div generated in a loop ?
I have two situations:
div 1 :
$('.div1').clone(true).insertAfter('.created_form');
div 2 :
loop
<div class="div2"></div>
endloop
I have a button in each div, to delete the div when the button is pressed.
But the button for delete work only for the cloned div (div1).
For div 2 is not working.
My code for deleting the div is :
$('.buttons').on('click', '.minus_sign', function() {
var parent_id = $(this).parent().attr('id');
$("#"+parent_id).remove();
$("input[name='"+parent_id+"']").remove();
});
Can someone tell me why this is not working for both please ? I mention that the div is exaclty the same, only the id is different! Thank you
That's because the one created without the clone doesn't have an id attribute.
<div class="div2"></div>
However, if you were give it an id:
<div id="myDiv" class="div2"></div>
it would work.
Assuming the original element had an id attribute, the one you're creating inside the loop doesn't have an id attribute as mentioned in this answer.
Even if it has one, since you're using .clone(true), the clone will have the data and event handlers of the cloned element.
But the one created inside loop does not contain the event handler.
And the event delegation will not work since you're delegating the click of .minus_sign to the button which is also dynamically created.
You should delegate the event handler to a static element, for example
$(document).on('click', '.buttons .minus_sign', function() {
var parent_id = $(this).parent().attr('id');
$("#"+parent_id).remove();
$("input[name='"+parent_id+"']").remove();
});
BTW, Since remove() method returns the removed element, you can do the above like
$(document).on('click', '.buttons .minus_sign', function() {
var parent_id = $(this).parent().remove().attr('id');
$("input[name='"+parent_id+"']").remove();
});

Function for adding and removing style on click and unfocus

I am trying to implement a function which changes style of element on click and remove it when unfocus. For ex: When element2 is clicked, it should remove class of other elements, and add class to the clicked element only.
<div class="dope" id="element777"></div>
<div class="dope" id="element2"></div>
<div class="dope" id="element11"></div>
<div class="dope" id="element245"></div>
<div class="dope" id="element60"></div>
.....(More are created automatically, numbers are not estimatable)
I couldnt know the element ids that are created. The only remains same is class.
I have tried this, but its an unprofessional approach.
$('#element1').click(function(){
$("#element1").addClass(dope2);
$("#element2").removeClass(dope);
$("#element3").removeClass(dope);
$("#element4").removeClass(dope);
});
$("#element1").blur(function(){
$("#element1").removeClass(dope);
});
$('#element2').click(function(){
$("#element2").addClass(dope2);
$("#element1").removeClass(dope);
$("#element3").removeClass(dope);
$("#element4").removeClass(dope);
});
$("#element2").blur(function(){
$("#element2").removeClass(dope);
});
What is the best approach for automating this function, instead of adding click and blur (unfocus) function to ALL of elements ?
You can listen for click events on any div with an id containing the word "element', then target its siblings elements (those that are not clicked, without referring to them by id). This might do it:
$("div[id*='element']").click(function(){
$(this).addClass('dope').siblings('.dope').removeClass('dope');
});
Your jQuery could be vastly simpler if you leverage this and siblings:
Instead of:
$("#element1").addClass(dope2);
$("#element2").removeClass(dope);
$("#element3").removeClass(dope);
$("#element4").removeClass(dope);
It could be:
$('.dope').click(
function() {
$(this).addClass(dope2).siblings().removeClass(dope);
}
);
NOTE:
Do you have a variable called dope with the class name, or is dope the class name? If it's the classname, you need to put it in quotes: $(this).addClass('dope2'), etc.
If you are removing the class dope, then will want to add a class you can always use to select these elements (so that when you remove dope, it continues to work).
Button part:
$("div").click(function(){
if($(this).hasClass("dope") || $(this).hasClass("dope2")){
$(this).addClass("dope2");
$(".dope").not($(this)).removeClass("dope");
}
})
Blur part:
$("div").blur(function(){
if($(this).hasClass("dope") || $(this).hasClass("dope2")){
$(this).removeClass("dope");
}
}
I would recommend using the :focus css selector rather than using javascript to do what you are doing... Read more here. Instead of having a click listener, the focus selector will take care of that for you and automatically remove the styling when the element is out of focus.

Finding all child elements with onmouseover

I have a xpath and I want to find all the child elements (even the nested child elements) which have onmouseover event attached to them. I am novel to Javascript and JQuery. Can someone please help me out?
For e.g. on the link, I want to get all the child elements with onmouseover for the first element with class crAvgStars.
$("yourElementSelector").mouseover(function(){
var children = $(this).children();
// OR
$(this).children().each(function(){
// DO something with each one...
});
});
http://api.jquery.com/children/

How correct create dynamiclly select with horizontal orientation?

I want danamically create select element in horizontal block. And have funny result. What is the correct way?
JSFiddle
You need to define where you want to append the new elements. For this, use .after(). And then you need to apply styles on the generated/modified controlgroup.
Demo here: http://jsfiddle.net/Palestinian/rKGtQ/
Code:
// append select menu after Button div
$("#Button_show_filters").after('<select id="sm"><option>Opt 1</option><option>Opt 2</option></select>');
// apply styles on select menu
$("#sm").selectmenu();
// add options to controlgroup
$( "#test" ).controlgroup( "option", "corners", true );
// create controlgroup
$( "#test" ).controlgroup().trigger('create');
controlgroup div ID is #test.
I think the main problem is that every time the "Push me!!" button is pressed, you are appending a select element with an id attribute of sm. Having multiple elements with the same id is invalid HTML and can cause problems with Javascript. See this question.
Namely, the $("#sm") line doesn't know which select you are trying to target.
Maybe you should try something like this:
$("button").click(function () {
$("#div_for_harakteristikinomenklatury_list").append('<select><option>Opt 1</option><option>Opt 2</option></select>');
$("#div_for_harakteristikinomenklatury_list select:last").selectmenu();
});
Also, you should get rid of the onclick attribute for the button. You don't need it. Passing the click handler to the click function should make the function run when the button is clicked.
Instead of using id you should use class and apply selctmenu only on last appended select element. Check this fiddle
$("button").click(function show_filters() {
//alert("Hello");
$("#div_for_harakteristikinomenklatury_list").append('<select class="sm"><option>Opt 1</option><option>Opt 2</option></select>');
$(".sm:last").selectmenu();
})
Updated Fiddle
change the $("#sm").selectmenu(); to $("select").selectmenu();
With above mentioned method no matter what is the id or class of the element you newly pushed, it'll get the styles applied.
Check the live fiddle here http://jsfiddle.net/mayooresan/VMj4U/6/

Get pointed elements with jquery

How to get the pointed item with jquery.I mean by pointed item, if the mouse click on some div in the body, i want to get that div's info , or click on a select box or etc.. so they are no tchoasen by me, the selected items are all html elements in the web, just i want to recieve the info of the element witch i have been clicked on.
$(document.body).click(function(ev) {
$(ev.target); // is the clicked element
});
Live Example
ev.target .click
http://api.jquery.com/category/events/event-object/
http://api.jquery.com/event.currentTarget/
Hmm, I am not sure if I understand your question but are you are refering to .html() method. The examples below will pop up the div's content upon click or hover.
Example
<div id='test'>Content of div</div>
//on click
$('#.test').click(function(){
alert($(this).html());
});
//on hover
$('#.test').hover(function(){
alert($(this).html());
});
Assume you have a div having id 'test' inside your body element. Register event by jQuery as:
$("div#test").click(function(event){
alert(event.target);
/*here event is the object fired, and target is the Div element i.e. source or you can use 'this' to refer to Div element*/
alert(this);
// Here 'event.target' and 'this' will give the same Div element.
});

Categories

Resources