Get the id of a the item that is clicked - javascript

I have this html code:
<b class = "edit" id = "foo1">FOO</b>
<b class = "edit" id = "foo2">FOO2</b>
<b class = "edit" id = "foo3">FOO3</b>
And I have this code in jQuery:
$('b.edit').click(function(){
//GET THE ID OF THE b.edit: e.g foo1, foo2, foo3
$('.editP').focus();
});
How can I get the id value of the b.edit, as there are multiple instances of b.edit, and I want to get the specific id of the one clicked? How can I do this?
Thanks, Sorry, I am pretty new to javascript.

I'm assuming from your sample code that you're using jQuery? If so you can get the id as follows:
$('b.edit').click(function(){
this.id;
});
EDIT:
The direct reference to the attribute is indeed more efficient if all that is required is simply the id.
Also can be obtained from the jQuery object:
$('b.edit').click(function(){
$(this).attr('id');
});
Sample fiddle: http://jsfiddle.net/5bQQT/

Try with this:
$('b.edit').click(function(e){ //When you use an event is better
//send the event variable to the
//binding function.
var id = e.target.id; //get the id of the clicked element.
/*do your stuff*/
$('.editP').focus();
});

try this. You can use keyword "this" to retrieve the attr ID...
$('b.edit').click(function(){
alert($(this).attr("id"));
});

$('.edit').click(function(){
var theId = $(this).attr('id');
}
This will get you the ID of anything clicked with a class of .edit

$('.edit').live('click', function() {
alert( this.id );
});
Sample
http://jsfiddle.net/ck2Xk/

When passing a click handler in JQuery, you actually have a reference to something called an event object. This event object has a property called target, which is a reference to the element that was clicked.
$('b.edit').click(function(eventObject){
eventObject.target // this is the element that was clicked.
});
Since you have a reference to the target element, you can do whatever you like. In this case, you could just access eventObject.target.id.

Since nobody has shown the simplest method yet that doesn't even need jQuery to get the id:
$('.edit').click(function() {
alert(this.id);
});
I never understand why people use jQuery for getting simple attributes which involves two jQuery function calls (and a bunch of overhead to create a jQuery object) instead of one direct attribute reference.

something like this:
var id = $(this).attr('id');
More clearly:
$('b.edit').live('click', function(){
var id = $(this).attr('id');
// in this scope this.id works too
// var id = this.id;
});

This is called event delegation in Javascript. More info can be found in Zakas blog http://www.nczonline.net/blog/2009/06/30/event-delegation-in-javascript/
The idea in few words is you attache the event to a parent node and then waiting for some event on the child node. In the example below I attach the onclick event to the document itself. Then inside the event handler you will write a switch statement to check the clicked element id, then do what you want to do for that element
document.onclick = function(event){
//IE doesn't pass in the event object
event = event || window.event;
//IE uses srcElement as the target
var target = event.target || event.srcElement;
switch(target.id){
case "foo1":
foo1();
break;
case "foo2":
foo2();
break;
case "foo3":
foo3();
break;
//others?
}
};
//some dummy handlers
var foo1 = function(){
alert("You clicked foo1");
};
var foo2 = function(){
alert("You clicked foo2");
};
var foo3 = function(){
alert("You clicked foo3");
};
For how to implement event delegation in jQuery you can check http://api.jquery.com/on/#direct-and-delegated-events

Even though this is not a real answer to your question. I will try to explain why what your asking is not the way to go. Since you are new especially, since learing bad practices could be hard to unlearn. Allways try to search for an ID before finding an element by its Class. Also try to avoid giving every element the same class (and in this case ID to), just give it an encapsulating parent.
Furthermore, the id of an element is really specific and should preferably used to find / select / bind events to. An id should usually be unique for this to work, so in your case a couple of things could be optimized, lets say like:
<div id="foo">
<b id="1">Foo</b>
<b id="2">Other foo</b>
<b id="3">Some foo</b>
</div>
Now if you want to know which was clicked there are multiple ways to accomplish it, but a nice one is simply binding a parent its children (i.e <div id="foo"> .. </div>). This way you can alter the structure of your pretty fast, without changing all the classes and id's.
With jQuery you can get the attribute id using the .attr() function. However I told you the id was pretty specific and thus has its own rights in javascript world. An id can also be directly targeted ('DOMelement.id', but this would be too much to explain for now)
In two ways the <b> can be targetted:
Example a)
var b_elements = $("#foo").children();
Example b)
var b_elements = $("#foo").find('b');
We can add jQuery (or javascript events) to these found elements. The nice thing about jQuery is that it simplifies alot of work. So in your case if you would like to know an id of a certain clicked <b> field you could use a very verbose way:
b_elements.click(function()
{
var clicked_element = $(this);
alert(clicked_element.attr('id'));
});
Verbose because you can do it much much shorter, but who cares about a few bytes when your learning and this makes remembering functions and events alot easier. Say you wanted to get the class edit by finding the where you knew the id that was clicked:
b_elements.click(function()
{
var clicked_element = $(this);
alert(clicked_element.attr('class'));
});
And to conclude, the id of an element is ment to be unique because it makes searching through big documents alot faster. Also don't forget to look and learn plain javascript, as it helps coding in jQuery alot too, but not the other way around. Your given question would require a for loop in plain javascript since it cannot do a lookup by class nor id nor have they have a common parent.
Good luck with learning :)

Related

How do you target an element that is dynamically generated? [duplicate]

Beginner to all of this, playing around with Firebase. Basically, I want to retrieve text entries from Firebase and have an "Approve" button next to it. When the button is clicked, I want that specific text entry to be pushed to a new Firebase location and the text removed from the page. I am creating the button and the text dynamically and I am having some trouble with selecting the button and the divs I created. I know I have to use on() but I'm unsure of how to use it.
Thanks!
approveRef.on('child_added', function(snapshot) {
var posts = snapshot.val();
$('<div id="post">').text(posts.text).append('<button style ="button" id="approve">Approve</button>').appendTo($('#feed'));
});
$('#approve').on("click", function(){
var text = $('#post').val();
postsRef.push({'text':text});
$('#post').remove();
});
You have to bind .on() on a container of your dynamically added element that is already on the page when you load it, and have it like this:
$('#yourContainer').on('click', '#approve', function(){
//your code here..
});
Your .on() didn't work, because you are adding the button dynamically. You can't find the dynamically added elements directly using that elements id selector like $('#approve'). So you should
bind .on() with $(document) selector. This will always contain your dynamically added elements.
$(document).on( eventName, selector, function(){} );
$(document).on('click','#approve',function(){
//your code here
});
I find a quick dip into the DOM, and then running back into jQuery very handy for this problem:
// Construct some new DOM element.
$(whatever).html('... id="mynewthing"...');
// This won't work...
$("#mynewthing")...
// But this will...
$(document.getElementById("mynewthing"))...
This works by turning the DOM object directly into a selector. I like it because the approach is transparent in operation/intent.
Another alternative, simpler to understand, less powerful, also perfectly valid, is to simply bind the event while you create the element:
approveRef.on('child_added', function(snapshot) {
var posts = snapshot.val();
var $button = $('<button style ="button" id="approve">Approve</button>');
$button.on("click", function(){
var text = $('#post').val();
postsRef.push({'text':text});
$('#post').remove();
});
$('<div id="post">').text(posts.text).append($button).appendTo($('#feed'));
});
Another problem you are going to run into, assuming there will be more than one of these on a page, is that you are using IDs in the records. They're going to clash if they aren't unique.
A great alternative is to refer to these items with data-* tags or other identifying characteristics, such as css tags. But in your case, you don't need them at all!
approveRef.on('child_added', function(snapshot) {
var posts = snapshot.val();
var id = snapshot.name();
var $button = $('<button style="button">Approve</button>');
$button.on("click", function(){
// use parent.closest(...) in place of an ID here!
var text = $(this).parent().closest('textarea').val();
postsRef.push({'text':text});
$(this).parent().remove();
});
/* just an example of how to use a data-* tag; I could now refer to this element using:
$('#feed').find('[data-record="'+id+'"]') if I needed to find it */
$('<div data-record="'+id+'">').text(posts.text).append($button).appendTo($('#feed'));
});
I don't sure exactly what are you looking for. You can use .find() to select dynamically elements. I think .find() will look at the html structure again to get needed elements.
$("#button").click(function(e){
$(".parentContainer").find(".dynamically-child-element").html("Hello world");
});
Or
$(".parentContainer").find(".dynamically-child-element").html("Hello world"); // not in click event
So this is my demo

Function hide() , prev() , show() are assembled to get required result but unable to understand its working?

I have got a script which works fine. The script is :
var minimized_elements = $('.innovision-msg');
var minimize_character_count = 100;
minimized_elements.each(function(){
var t = $(this).text();
if(t.length < minimize_character_count ) return;
$(this).html(
t.slice(0,minimize_character_count)+
'<span>...</span>'+'Read more'+
'<span style="display:none;">'+ t.slice(minimize_character_count ,t.length)+ '<span>...</span>' +
'Read less</span>'
);
});
$('a.read_more', minimized_elements).click(function(event){
event.preventDefault();
$(this).hide().prev().hide();
$(this).next().show();
});
$('a.read_less', minimized_elements).click(function(event){
event.preventDefault();
$(this).parent().hide().prev().show().prev().show();
});
Here in this script i can not understand the meaning and use of code:
$(this).parent().hide().prev().show().prev().show();
Can any one explains what this line of code means ?
Moreover when it set var minimize_character_count = 250; Script does not works.
$(this).parent().hide().prev().show().prev().show();
This line is hiding the parent element of this element which is clicked (for minimization). After hiding the parent element, it goes to the previous sibling (of the parent element) and make it visible. It again goes to the previous sibling (of the previous sibling of the parent element) and make it visible.
Basically, jquery methods (after doing their job, whether to hide, show or traverse) returns the reference to the current element which allows you to chain the methods in this manner.
This is basically chaining which works on an returned object
$(this).parent().hide().prev().show().prev().show();
$(this) referring to either 'a.read_less', minimized_elements
On click on this element , it will find the parent dom and will hide it.
.prev() is use to select the previous element. So it will select the previous element and will show it. Again using prev() will select previous to previous element and will also show it
Method chaining is one of the nice features of jQuery. Most of the methods will return objects on which it is called, and hence you can call other methods in same chain.
Yet another one of the really cool aspects of jQuery is the fact that
most of the methods returns a jQuery object that you can then use to
call another method. This allows you to do command chaining, where you
can perform multiple methods on the same set of elements, which is
really neat because it saves you and the browser from having to find
the same elements more than once - source

Event delegation issue with JQUERY

I am new in Jquery and I am trying to understand how event delegation work.
I am trying this:
$("#32298").on( 'click',function() { // event delegation
alert("df");
var imgs = document.getElementById("32298")[0].src;
alert(imgs);
});
When I click on the image with this Id I get the first alert but it doesn't work the second alert.
What am I doing wrong here?
Thank you.
If you want to perform event delegation then the second argument of the event handler function needs to be a selector to match the element that matches the one you want to be clicked.
$(document.body).on('click', "#32290", function(event) {
The problem with your code has nothing to do with event delegation. getElementById returns a single element (an id must be unique in the document), not a HTML Collection. (Compare with getElementsByTagName and getElementsByClassName which use the plural Elements.) It won't have a 0 property.
var imgs = document.getElementById("32298").src;
Since you're using jQuery, you can simply use the $(this) constructor, rather than document.getElementById():
$("#32298").on( 'click',function() {
alert("df");
var imgs = $(this).attr('src');
alert(imgs);
});
For what it's worth, this isn't event delegation by the way, it's just an event bound to an element.
If you must use vanilla JS to fetch the src attribute, you don't need to pass an index to the returned value of getElementById(), since this function returns a DOMObject, not an array. Update as follows:
$("#32298").on( 'click',function() {
alert("df");
var imgs = document.getElementById("32298").src;
alert(imgs);
});
It's also worth noting that IDs should be unique, so #32298 should reference a single element in the DOM. I don't know whether it's a typo, but it appears that you may have multiple elements with the same ID (since you use the variable name imgs - i.e. plural).
you can try this
$("#32298").click( function() {
alert("df");
var imgs = $(this).attr('src');
alert(imgs);
});

Add an id to a dynamically created element

I'm trying to add an id to an element that I create dynamically using javascripts' document.createElement() method. Basically I want to create an iframe in my html document and at the same time give that newly created element an id.
Here's my code so far. I've figured out how to put the element in the DOM and all that, i just need the id.
function build(content){
var newIframe = document.createElement("iframe");
var newContent = document.createTextNode("Hello World!");
newIframe.appendChild(newContent);
var element = document.getElementById("container");
document.body.insertBefore(newIframe, element);
document.getElementsByTagName("iframe").id = "active";
};
As you can probably see, I have tried to give it an id at the very end. Problem is, it doesn't work.
So if anyone has any idea of what is wrong here, or an alternative way of doing what I want to do, please feel free to express yourself. Many thanks!
Just add an attribute (id is an attribute) to that element directly, like this:
var newIframe = document.createElement("iframe");
newIframe.id = 'active';
... although it looks quite strange to have id equal to active (too generic for a unique identifier).
Your current approach doesn't work because document.getElementsByTagName("iframe") returns a collection of elements - NodeList or HTMLCollection (it's browser-dependant). While you can assign a value to its id property, it won't do what you mean to. To make it work, you can adjust it this way:
document.getElementsByTagName("iframe")[0].id = "active";
... but, as shown above, there's a better way.
newIFrame.setAttribute("id", "something");

Javascript/jQuery - How do I obtain name of the class of clicked element?

I googled and googled and I concluded that it's very hard to get answer on my own.
I am trying to use jquery or JavaScript to get a property of clicked element. I can use "this.hash" for example - it returns hash value I presume.
Now I would like to get name of the class of clicked element.
Is it even possible? How? And where would I find this kind of information?
jQuery documentation? - All I can find is methods and plugins, no properties.. if its there - please provide me with link.
JavaScript documentation? - is there even one comprehensive one? again please a link.
DOM documentation? - the one on W3C or where (link appreciated).
And what is this.hash? - DOM JavaScript or jQuery?
In jQuery, if you attach a click event to all <div> tags (for example), you can get it's class like this:
Example: http://jsfiddle.net/wpNST/
$('div').click(function() {
var theClass = this.className; // "this" is the element clicked
alert( theClass );
});
This uses jQuery's .click(fn) method to assign the handler, but access the className property directly from the DOM element that was clicked, which is represented by this.
There are jQuery methods that do this as well, like .attr().
Example: http://jsfiddle.net/wpNST/1/
$('div').click(function() {
var theClass = $(this).attr('class');
alert( theClass );
});
Here I wrapped the DOM element with a jQuery object so that it can use the methods made available by jQuery. The .attr() method here gets the class that was set.
This example will work on every element in the page. I'd recommend using console.log(event) and poking around at what it dumps into your console with Firebug/Developer tools.
jQuery
​$(window).click(function(e) {
console.log(e); // then e.srcElement.className has the class
});​​​​
Javascript
window.onclick = function(e) {
console.log(e); // then e.srcElement.className has the class
}​
Try it out
http://jsfiddle.net/M2Wvp/
Edit
For clarification, you don't have to log console for the e.srcElement.className to have the class, hopefully that doesn't confuse anyone. It's meant to show that within the function, that will have the class name.
$(document).click(function(e){
var clickElement = e.target; // get the dom element clicked.
var elementClassName = e.target.className; // get the classname of the element clicked
});
this supports on clicking anywhere of the page. if the element you clicked doesn't have a class name, it will return null or empty string.
$('#ele').click(function() {
alert($(this).attr('class'));
});
And here are all of the attribute functions.
http://api.jquery.com/category/attributes/
You can use element.className.split(/\s+/); to get you an array of class names, remember elements can have more than one class.
Then you can iterate all of them and find the one you want.
window.onclick = function(e) {
var classList = e.srcElement.className.split(/\s+/);
for (i = 0; i < classList.length; i++) {
if (classList[i] === 'someClass') {
//do something
}
}
}
jQuery does not really help you here but if you must
$(document).click(function(){
var classList =$(this).attr('class').split(/\s+/);
$.each( classList, function(index, item){
if (item==='someClass') {
//do something
}
});
});
There's a way to do this without coding. Just open the console of your browser (f12?) and go to element you want. After that, hover or click the item you want to track.
Every change done on the DOM will be for a few seconds marked (or lightened) as another color on the console. (Watch the screen capture)
On the example, each time I hover a "colorItem", the 'div' parent and the "colorItem" class appears lightened. So in this case the clicked class will be 'swiper-model-watch' or 'swiper-container' (class of the lightened div)

Categories