Get Selector from a JQuery object - javascript

For Example, this will give me:
console.log($(".smartgridview-normal").selector)
//result is '.smartgridview-normal'.
My code is :
$( '.smartgridview-normal th' ).live( 'dblclick', function () {
var optimalWidth = parseFloat( $( this ).attr( 'data-width' ) );
console.log( $(this).selector );// At this point I need the selector
$(this).addClass('selected');
} );
My Log is giving me an empty string. There is no selector for 'this' object. Is there any way to get the selector of the element which 'this' is pointing to?
Thanks for your time.

Oh, I see where your problem is. $(this) is not constructed using a selector, but rather by directly wrapping a DOM element, so it does not carry it anywhere. You can get the original selector obviously by doing $('.smartgridview-normal th').selector; but there's a big difference between $('.smartgridview-normal th') and $(this).

As Amadan said, inside the click handler this refers to the element, not the jQuery object
It's not perfect, but you could cache the jQuery object
var elements = $("#mySelector")
$elements.on("dblclick", function(event){
console.log($elements.selector);
});​
Fiddle for testing

To elaborate on my comment, "#"+this.id is the best you can hope for if the element has an id. If not, the only information you have is that the element belongs to your original selection '.smartgridview-normal th'.
You could always add the id yourself within the code (for example unique id based on the current date and time).

Try using nodeName instead of selector,
var selector = $(this)[0].nodeName;
Or,
var selector = this.nodeName;

Perhaps set it to a variable first?
var sel = "answer";
$("#"+sel).on("dblclick", function(event){
console.log("Current selector is "+sel);
});​

Related

jQuery adding new DOM elements having attributes within an element of specific id

Is there a methodToCreate in jQuery which could be written as
$("#someId").methodToCreate("tagName", ".className");
where an element with tag tagName would be added and given a class className and that too inside a specific element which would have an id someId?
$("<tag></tag>").addClass("className").attr({id: 'someId'}).appendTo( "body" )
Here's and example setting all the attributes individually.
As pointed out such function doesn't exist, but you could always create one .
(function( $ ){
$.fn.methodToCreate= function(tagName,className,id) {
$(id).append("<"+tagName+" "+"class="+"\'"+className+"\'>"+"SampleContent"+"</"+tagName+">");
return this;
};
})( jQuery );
and you can call this whenever you want in the following manner :
$(document).ready(function(){
$(document).methodToCreate('p','sampleClass','#someId');
});
Using this function(methodToCreate) you can dynamically pass the tagName , className and id of the element that you want to append to.
Here is the working fiddle : https://jsfiddle.net/varunsinghal65/udrxeg9m/1/#&togetherjs=TBEnLAnNzJ
Using jQuery you can create an element
var el = $('<tagName class="className"/>');
and then add it to a container
$('#someId').append(el);
$('#someId').append('<tagname class="className"></tagname>');
if you have the class stored in a variable (for example myClass) don't forget to quote it like this:
$('#someId').append('<tagname class="' + myClass + '"></tagname>');
No that method does not exist, but you can use .appendTo
like:
$("<tagName class='className'></tagName>").appendTo("#someId");
Hope it helps.

$(this) throws "undefined" but this works as intended

Please, consider two pieces of code.
1) Works as intended:
$(function(){
$('.menu li').on('click', function(){
var choice = document.getElementById("choice");
var text = this.textContent;
choice.textContent = text;
});
});
2) In this case, $(this) throws "undefined".
$(function(){
$('.menu li').on('click', function(){
var choice = document.getElementById("choice");
var text = $(this).textContent;
choice.textContent = text;
});
});
I've been using $(this) as a reference to selected element for a long period of time. But today it failed. What's wrong? Should I forget about $(this) and never more be facing such a case in a few lines of simple code?
Codepen
The .textContent is a DOM property, not a jQuery property or method. This is why $(this), which is a jQuery element, does not have it.
You can use $(this)[0] to get the actual DOM property out of the jQuery element, like that:
var text = $(this)[0].textContent;
However $(this)[0] is equivalent to this so there's no point doing so in that specific example. It might make sense in other cases - for example, if you get a jQuery element as a function argument:
function set_text(jqElem,txt) { jqElem[0].textContent = txt; }
You can also use the jQuery method .text() to get or set the text content of the element, like that:
var text = $(this).text();
$() is the jQuery constructor function.
but this is a reference to the DOM element of invocation.
$(this), you are just passing the this in $() as a parameter so that you could call jQuery methods and functions.

jQuery .text() on multiple elements within the same class

I'm attempting to use .text() on multiple (unknown number of) elements on a page.
Consider:
<div class="myClass">element1</div>
<div class="myClass">element2</div>
<div class="myClass">element3</div>
and
$(document).ready(function(){
$( ".myClass" ).click(function() {
var text = $('.myClass').text()
alert(text)
});
});
The problem is, the .text() will return all the elements at the same time (in this example: "element1element2element3").
I'd need to return only the text within the clicked class, for example: click on element2, it returns "element2" as .text().
Context is key.
Event callbacks are run in the context of the trigger element. In other words, this points to that element. So instead of repeating the selector, as you currently are (unnecessarily wasteful in terms of performance), reference this:
$( ".myClass" ).click(function() {
var text = $(this).text(); //this === the clicked element
console.log(text);
});
Use $(this):
$(document).ready(function(){
$(".myClass").click(function() {
var text = $(this).text();
console.log(text);
});
});
Inside event callback this refers to the current (i.e. clicked) element.
Also, console.log() is better for debugging than alert().
Although there are answers already been posted but I would post mine with little explanation:
See, currently you have bound an event on class selector and in the web browser class selector returns a collection. So, that means there will be more than one element in the list.
More additions to this there are tag name selectors too which also returns a collection.
While on the other selector ID selector returns only one element always because as per standards or better to say as per rule IDs should have to be unique for each element. And that's why it always returns a single element from the DOM.
That's the reason you get different behavior. To overcome this issue you need to understand the context of the selector. Which is a good topic to get info about this.
So, this represents the DOM node and in your case you need jQuery object. So, wrap it with jQuery wrapper $() to have a jQuery object with $(this).
$( ".myClass" ).click(function() {
var text = $(this).text(); // the elem in context
console.log(text);
});
You can use the event object to find out which element is clicked and then can show it's text
$(document).ready(function(){
$( ".myClass" ).click(function(event) {
var text = $(event.target).text()
alert(text)
});
});
JSFIDDLE

Getting access to a jquery element that was just appended to the DOM

I am simply appending an element that is on the DOM like:
$("#div_element").append('test');
Right after I append it I need access to the element I just made in order to bind an click function to it, I tried:
$("#div_element").append('test').click(function(){alert("test")});
But the above didn't work. I could uniquely id the element but that seems like a bit to much work when perhaps there is a way I can get the element right after I append it.
You can do this:
var el = $('test');
$("#div_element").append(el);
el.click(function(){alert("test")});
// or preferrably:
el.on('click', function(){alert("test")});
The append function accepts two types of arguments: a string or a jQuery element.
In case a string is passed in, it will create a jQuery element internally and append it to the parent element.
In this case, you want access to the jQuery element yourself, so you can attach the event handler. So instead of passing in the string and let jQuery create an element, you have to create the element first and then pass it to the append-function.
After you've done that, you still have access to the jQuery element to be able to attach the handler.
var $a = $('<a />', {href:"#"})
.text("test")
.on('click', function(e) {
alert('Hello')
})
.appendTo('#div_element');
http://jsfiddle.net/33jX4/
Why not save a reference to the new element before you append it:
var newElement = $('test');
$("#div_element").append(newElement);
newElement.click(function(){alert("test")});
The last element would be the new element
$('a:last','#div_element').on('click',function(){
// do something
});
Add identity to that element then use it as follows
$("#div_element").append('<a id="tester" href="#">test</a>');
$('#tester').on('click', function(event) {
console.log('tester clicked');
});
You can attach event to element when you create it --
var ele =$("<a href='#'>Link</a>");
ele.on("click",function(){
alert("clicked");
});
$("#div_element").append(ele);
Just attach the click handler to the anchor BEFORE you append it.
$("#div_element").append($('test').click(function(){alert("test")}));

Reference to current object in Jquery chain

The following chain works:
$("</p>").html('message').hide().appendTo("#chat").fadeIn()
.parent().scrollTop($('#chat')[0].scrollHeight);
But this doesn't:
$("</p>").html('message').hide().appendTo("#chat").fadeIn()
.parent().scrollTop($(this)[0].scrollHeight);
this.scrollHeight doesn't work too.
How can i get current object reference in jquery chain?
You only get access to the current object inside of a callback. There's no way you can get access to the current object in your chain.
Try this:
var $parent = $("</p>").html('message').hide().appendTo("#chat").fadeIn().parent();
$parent.scrollTop($parent[0].scrollHeight);
If you really don't want to break out of you chain, you can re-select:
$("</p>").html('message').hide().appendTo("#chat").fadeIn()
.parent().scrollTop($("#chat")[0].scrollHeight);
But I'd strongly advise you against it. There's no need to select the same DOM element twice.
In your second code snippet this doesn't point to #chat that's why it doesn't work. this mostly points to the calling function instance or the object which triggered any event.
You can try something like this
var $p = $("</p>").html('message').hide().appendTo("#chat");
$p.fadeIn().parent().scrollTop($p[0].scrollHeight);
Well, it's obvious. The #chat element is a static element and you are dynamically appending paragraphs to it. Therefore, you want to get a reference to that element beforehand (for instance, on page initialization):
var chat = $( '#chat' )[0];
Now, you do this:
$( '<p />' ).html( 'message' ).hide().appendTo( chat ).fadeIn();
$( chat ).scrollTop( chat.scrollHeight );
So, the idea is to retrieve references to the main static elements (chat-box, toolbar, panel, navigation, etc.) on page initialization, and then use those references all over your application code.

Categories

Resources