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.
Related
I am trying to get a text content inside a div using jquery. But it returns 'undefined'. Please someone tell me what i'm doing wrong here. this is my code.
<a><div class="exc_text">Some text here</div></a>
$(document).on('click','.exc_text',function(){
var text = $(this).textContent;
console.log(text);
});
textContent is a property on native elements, not on jQuery objects. $(this) wraps this (which is a native DOM element) in a jQuery object.
Either stick to the native DOM api (and go with textContent) - which is what I'd recommend:
document.addEventListener('click', (e) => {
if (e.target.classList.contains('exc_text') {
console.log(e.target.textContent);
}
})
Or stick with jQuery if you have to (and use .text()):
$(document).on('click', '.exc_text', function(){
var text = $(this).text();
console.log(text);
});
You're reselecting the element with jQuery which you don't need to do. Try this
$(document).on('click','.exc_text',function(){
var text = this.textContent;
console.log(text);
});
The easiest way to solve this is to look in dev tools. All i did was break on the second link, and hovered over this, which showed me that it was an element so no need to reselect it...
You should use .text() instead of .textContent
<a><div class="exc_text">Some text here</div></a>
$(document).on('click','.exc_text',function(){
var text = $(this).text();
console.log(text);
});
Just simply use .text()
<a><div class="exc_text">Some text here</div></a>
$(document).on('click','.exc_text', function(){
var text = $(this).text();
console.log(text);
});
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
I am very confused on how this works:
$(this).val()
It seems to be returning the value in a HTML tag. How could I make this return the name tag?
Assuming that this is a node or jQuery object:
$(this).attr('name');
You can use
$(this).attr('name');
In jQuery, the element being acted upon is often passed to the function parameter of a jQuery function as this. It can be made into a jQuery element object by using $(this) in the function parameter, ex:
$('.menu a').each(function(){
$(this).animate({paddingLeft: $(this).width()}, 200);
});
Font: http://www.dynamicdrive.com/forums/showthread.php?42053-jQuery-%28this%29-usage
If you have this code:
$("#someItem").click(function(){
$(this) -> returns $("#someItem");
});
If you want the name attribute, try:
$(this).attr("name");
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);
});
I am storing a div which gets selected
var selectedCell = null;
$(".selectableBox").on('click', function (event) {
selectedCell = $(this);
}
Later I want to hide one of selectableCell's children name selectableCellChild
$('#deleteConfirmed').on('click', function (event) {
selectedCellList.($'selectableCellChild').hide();
});
How can I correctly hide this child div? I know the syntax of the above example isn't right, and I have tried it many ways including using children() and next() methods of selectedCellList
selectedCellList.find('{selectableCellChild}').hide();
Where selectableCellChild is a placeholder for the real selector of the cell.
I have tried it many ways including using children() and next()
children - traverse only one level deep.
find - traverse the all the DOM levels deep.
next select the next immediate sibling.
For the second part, this is what you want:
$('#deleteConfirmed').on('click', function (event) {
$(selectedCellList).find('.selectableCellChild').hide();
});
If I understood correctly, you are trying to hide the children of clicked div. Try like below,
var selectedCell = null;
$(".selectableBox").on('click', function (event) {
selectedCell = $(this);
}); //Your missed );
$('#deleteConfirmed').on('click', function (event) {
//v-- Changed from selectedCellList to selectedCell as this is the clicked div.
selectedCell.find('.selectableCellChild').hide();
//assuming selectableCellChild-^ is class of child elements in the clicked div
});
Use .find.
selectedCellList.find('selectableCellChild').hide(); // I hope selectableCellChild isn't your real selector, it won't work
Also, when declaring your variable, make it a jQuery object since you intend to store a jquery object in it to avoid undefined method errors.
var selectedCell = $();