How to get the this DOM Object from the $(this) jQuery Object? - javascript

I have a function to which a jQuery object is passed as an argument. See below code.
$('selector').click(function() {
// $(this) is the jquery object for the DOM on which I clicked.
test($(this));
});
function test(jqobj) {
// Here from jqobj, I want to get back the native javascript object (I mean the this)
}

The jqobj param is an array of DOM elements so you can use
jqobj[0]
but test the size of the array if it is not empty like
jqobj.length > 0

So we can covert each other
//From jQuery object to Dom:
var domobject = jqueryObject.get();
//From Dom to jQuery object
var jqueryObject = jQuery(domobject);
Example:
//From Dom to jQuery object
var overlayContent = document.createElement("div");

var __this=this; //declare out side your function.
function test(){
__this; //use __this in your function.
}

if you are sure that there will only be one element then
function test(jqobj) {
var el = jqobj[0]
}

rather passing object as a parameter you can also send element id or class to function.Then you can use getElementById method inside function to refer the element.

If you are not passing multiple element use like this:
function test(jqobj) {
var obj;
if(jqobj[0]!=null)
{
obj = jqobj[0];
}
}

Related

Get class attribute list [duplicate]

I know you can SET multiple css properties like so:
$('#element').css({property: value, property: value});
But how do I GET multiple properties with CSS?
Is there any solution at all?
jquery's css method (as of 1.9) says you can pass an array of property strings and it will return an object with key/value pairs.
eg:
$( elem ).css([ 'property1', 'property2', 'property3' ]);
http://api.jquery.com/css/
Easiest way? Drop the jQuery.
var e = document.getElementById('element');
var css = e.currentStyle || getComputedStyle(e);
// now access things like css.color, css.backgroundImage, etc.
You can create your own jQuery function to do this:
​
//create a jQuery function named `cssGet`
$.fn.cssGet = function (propertyArray) {
//create an output variable and limit this function to finding info for only the first element passed into the function
var output = {},
self = this.eq(0);
//iterate through the properties passed into the function and add them to the output variable
for (var i = 0, len = propertyArray.length; i < len; i++) {
output[propertyArray[i]] = this.css(propertyArray[i]);
}
return output;
};
Here is a demo: http://jsfiddle.net/6qfQx/1/ (check your console log to see the output)
This function requires an array to be passed in containing the CSS properties to look-up. Usage for this would be something like:
var elementProperties = $('#my-element').cssGet(['color', 'paddingTop', 'paddingLeft']);
console.log(elementProperties.color);//this will output the `color` CSS property for the selected element

javascript - insert div after elements with a certain class on mouseover

I know that there is a really simple jQuery way to to this, but now I would like to understand why my code is not working properly:
function insertAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
var menuHelp = document.querySelector(".menu_help");
for (var i = 0;i<menuHelp.length;i++){
menuHelp[i].onmouseenter = function(){
menuHelpPopup = document.createElement("div");
menuHelpPopup.setAttribute('class','menu_help_popup');
menuHelpPopup.innerHTML = "test";
insertAfter(menuHelp[i], menuHelpPopup);
}
menuHelp[i].onmouseleave = function(){
menuHelpPopup.remove();
}
}
What I'm trying to do is to create a popup and insert it after elements with a certain class when mouseover on them..
DEMO http://jsfiddle.net/r5e8rvkg/
Please make sure menuHelp is a nodeList, so you should use document.querySelectorAll;
When the mouse enter, the value of i is menuHelp.length. so you should use this, like insertAfter(this, menuHelpPopup)
I used getElementsByClassName and it seemed to have worked.
var menuHelp = document.getElementsByClassName('menu_help');
Please checkout here: http://jsfiddle.net/r5e8rvkg/1/
First, use querySelectorAll instead of querySelector.
More importantly, you need to take care that in your code:
menuHelp[i].onmouseenter = function(){
menuHelpPopup = document.createElement("div");
menuHelpPopup.setAttribute('class','menu_help_popup');
menuHelpPopup.innerHTML = "test";
insertAfter(menuHelp[i], menuHelpPopup);
}
The value i would not be passed in correctly because the event onmouseenter is Async. When the function is called, the value of i is actually i === menuHelp.length, which results in menuHelp[i] === undefined.
You need to use Closure, as shown in my JSFiddle code.
The document.querySelector() method returns only the first element with the specified selector. To get each element with class 'menu_help', you need to use the document.querySelectorAll() method.
In other words, replace:
var menuHelp = document.querySelector(".menu_help");
With
var menuHelp = document.querySelectorAll(".menu_help");

jQuery appendTo does not work under $.post

// plays a card into table.
// this code works. rendered card is appending into the table.
var playCard = function(card){
var renderedCard = renderCard(card);
$('#'+renderedCard.id).appendTo('#flop');
// but this one does not work.
var playCom = function(){
$.post('/api/comPlay', function(data){
var renderedCard = renderCard(data.card);
$('#'+renderedCard.id).appendTo('#flop');
});
};
I check the returned value from $.post. data.card gives the correct value. I create a div html with my renderCard function. That function works correctly as you see. But under $.post not.
I am stuck. Is there something special that i must know about $.post?
Thank you.
update :
var renderCard = function(card){
var create = document.createElement('div');
create.className = 'cardBig';
create.id = card;
return create;
};
You don't need to "find" your newly-created DOM element.
$(renderedCard).appendTo('#flop');
should do it.
Also, since you're using jQuery anyway:
$('#flop').append($('<div/>', {
className: 'cardBig',
id: data.card
}));
will save you the extra function.
In renderCard() method you are just creating a new html element but it is not rendered to the dom.
So your element lookup $('#'+renderedCard.id) will not work
$(renderedCard).appendTo('#flop');
have you tried selecting the id element first, like so:
$(renderedCard).appendTo( $('#flop')[0] )

Jquery comparing elements

I have an array on javascript and i insert the elements on it like this:
var parentRow = $(button).parent().parent();
list.push({ parent: parentRow, detailRow: newRow });
On the click of another button i do the following:
var parentRow = $(button).parent().parent();
var detailRow = null;
for (var i in list) {
if ($(list[i].parent) == $(parentRow)) {
detailRow = list[i].detailRow;
}
}
The point is: The if comparing to two elements should return TRUE, because they are the same DOM element....the same i added before, but it return FALSE.
I would like to know how i compare this two elements to get TRUE there.
Try:
if (parentRow.has(list[i])) {
They are not the same objects, because they don't refer to the same jQuery instance.
Simple solution: Don't use jQuery and do it with normal DOM methods.
jQuery solution: Use .is()
You need to compare the native elements, not the jQuery-wrapped elements. jQuery's DOM methods returns not the elements themselves but a jQuery object.
if (list[i].parent[0] === parentRow[0]) {

JQuery on dynamically creating element and attaching data does not return value when calling data() again using selector?

I create a div element dynamically and associate data() to it. When accessing it again via selector it does not return the data. As result of below snippet I see first alert with data '1' and another with 'null' value. Can someone please help.
var dc = 0;
$("#attachData").click(function () {
dc++;
var newDiv = jQuery('#oldid').clone();
newDiv.attr('id', 'dt'+dc);
jQuery.data(newDiv, "dd", '1')
alert(jQuery.data(newDiv, "dd"));
var divFromSelector = $('#dt'+dc);
alert(jQuery.data(divFromSelector, "dd"));
});
Sorry, I did not add it in the snippet but its attached to the tree:
newDiv.attr('id', 'dt'+dc).
appendTo('#workspace-container');
Also when I try to access it using selector the element is returned correctly - but no data found.
Try:
var dc = 0;
$("#attachData").click(function () {
dc++;
var newDiv = jQuery('#oldid').clone();
newDiv.attr('id', 'dt'+dc).appendTo('#workspace-container');
jQuery.data(newDiv[0], "dd", '1')
alert(jQuery.data(newDiv[0], "dd"));
var divFromSelector = $('#dt'+dc);
alert(jQuery.data(divFromSelector[0], "dd"));
});
From the docs it seems that the JQuery.data method expects a DOM element, not a JQuery object. Appending [0] to a JQuery object gives the DOM element it is wrapping.
It'd probably be better if you used newDiv.data(...) and divFromSelector.data(...).
Demo here.
It looks like you haven't attached the new node in the DOM your accessing. http://api.jquery.com/clone/

Categories