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
Related
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")}));
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 have some search results that I'm outputting that are of this form:
<div id="result" title="nCgQDjiotG0"><img src="http://i.ytimg.com/vi/nCgQDjiotG0/default.jpg"></div>
There is one of these for each result. I'm trying to detect which one is clicked and then do some stuff. Each result has a unique title, but the same id. How do I use .click() to know which one was clicked so I can get it's ID and use it?
Here's how I'm getting the HTML from above:
$.each(response.data.items, function(i,data)
{
var video_id=data.id;
var video_title=data.title;
var video_thumb=data.thumbnail.sqDefault;
var search_results="<div id='result' title='"+video_id+"'><img src='"+video_thumb+"'></div>";
$("#searchresults").append($(search_results));
I tried
$('div').click(function(){
alert(this.id);
});
and the alert says "searchresults" (no quotes).
Additionally, this is the perfect opportunity to make use of event delegation. With this technique, you do not have to worry about re-binding click handlers after programmatic insertion of new DOM elements. You just have one handler (delegated) to a container element.
$("#searchresults").delegate("div", "click", function() {
console.log(this.id);
});
See .delegate
You can't have the same ID on multiple tags. You will have to fix that. You can use the same class, but there can only be one object in the page with a given ID value.
this.id will fetch the id value of the item clicked on and this should work fine once you get rid of conflicting IDs:
$('div').click(function(){
alert(this.id);
});
This code should be something this:
var search_results="<div id='result'" + video_id + " title='"+video_id+"'><img src='"+video_thumb+"'></div>";
$("#searchresults").append(search_results);
to coin a unique id value for each incarnation and append will just take the string - you don't need to turn it into a jQuery object.
you could get the title using $(this).attr("title").val()
This question is in continuation to How to get attributes of container in jQuery, I have different containers on my webpage and all of them have <div id = "some values">. Now how can I get attributes values separately for each component?
Is there any way I can know which attribute id belong to which container div?
Currently I am using:
var id = $( '.promotion' ).attr( 'id' );
But if I have multiple promotional components on page and all have same div attribute as id than how can I relate that this particular attribute id belonged to this specific container?
Update: I am having a function which is called for each container present on the page and so if I am using above mentioned code than will it not always return me the first match for id in the div and would never go to other divs and so I will always get same value for id which is for the first container ? If so than what is the work around for this ?
var id = $( '.promotion' ).this.attr( 'id' );
var id = $( '.promotion' ).$this.attr( 'id' );
var id = this.$( '.promotion' ).attr( 'id' );
How would I know if the attribute value is for current container, so how should I use this properly to get this information ?
Hope this question is clear.
You can loop through and process each div individually
$(".promotion").each(function() {
var id = this.id; // 'this' is the html element, not the jquery object
});
Update
function myfunc() {
alert(this);
}
// inside myfunc, this will be the window
myfunc();
// call (also: apply()) changes "this" to be the first argument
myfunc.call(document.getElementById("someid"));
Jquery uses this to refer to the current element being processed. In events that would be the target element. In .each it is the current element in the collection.
Consider:
$(".promotion").click(function() {
alert(this); // will alert with the div that was clicked
});
In Jquery you can wrap any html element with a JQuery Object by using $(element). So when this is an html element like in the example above you can use $(this):
$(".promotion").click(function() {
alert($(this).attr("id")); // will alert with the div that was clicked
});
Play around with it here: http://jsbin.com/okuri3/edit.
More about this:
http://www.quirksmode.org/js/this.html
http://remysharp.com/2007/04/12/jquerys-this-demystified/
I am not very sure with the use of "this" [current context] in jquery.What I know is- it prevents the dom from searching all the elements, it just work on that current element, which improve performance[correct me if I am wrong].Also I am not sure when to use this and when not.
lets say, should I go for
$("span",this).slice(5).css("display", "none")
or
$("span").slice(5).css("display", "none")
both will work, but I am not very clear as how really it works.can somebody explain it with a diff/proper example, and when to use what?
[EDIT]
$(function() {
$("#clickme").click(function() {
$("span",this).slice(5).css('display', 'block');//doesn't work ? why?
$("span").slice(5).css('display', 'block');//works..why?
});
});
enter code here <span id="clickme">Click me</span>
<span>itam1</sapn>
<span>itam2</sapn>
<span>itam3</sapn>
<span>itam4</sapn>
<span>itam5</sapn>
...upto10
Usually you can use the this keyword on event handlers since it will be a reference to the element that triggered the event and other jQuery functions like $.each.
For example when handling a click event lets say:
$('.parentElement').click(function () {
$('.foo', this).hide();
});
The above code, will hide all the elements with class foo that are descendants of the currently parentElement that was clicked.
The use of the context argument of the jQuery function is the equivalent of making a call to the find method:
$(expr, context);
// is just equivalent to:
$(content).find(expr);
EDIT: Looking at your example:
$("#clickme").click(function() {
$("span",this);//... (1)
$("span");//.. (2)
});
The first line, will look for all the span elements that are inside of #clickme (its descendants), since that element was the one that triggered the click event.
The second line, will look for all the span elements on the whole page.
How it works
Lets use this HTML for the examples:
<div id="container">
<div class="column">Link 1</div>
<div class="column">Link 2</div>
</div>
<div id="footer">
Link 3Link 3
</div>
The scoping parameter of the jQuery function should only be used if you already have a cached reference to a DOM element or jQuery wrapped element set:
var $set = $('#container');
$('a', $set).hide(); // Hides all 'a' tag descendants of #container
Or in an event:
$("#container").click(function(e){
$('a', this).hide(); // Same as call above
}
But it makes no sense to use it like this:
$('a', '#container').hide()
When it should be written like this:
$('#container a').hide();
Having said all that, it is generally cleaner and clearer to just use .find() instead of using the second parameter in the jQuery function if you already have the jQuery or DOM element. The first example I gave would be written this way instead:
var $set = $('#container');
$set.find('a').hide(); // Hides all 'a' tag descendants of #container
If this one call was the only reason you grabbed the #container object, you could also write it this way since it will still scope the search to the #container element:
$("#container a").hide(); // This is the same as $('a', "#container");
Why would you scope your selections
When jQuery looks for an unscoped selector, it will search through the entire document. Depending on the complexity of the selector, this could require a lot of searching. If you know that the element you are looking for only occurs within a specific parent, it will really speed up your code to scope the selection to that parent.
Regardless of what method of scoping you choose, you should always scope your selectors whenever possible.