In the code below and demo here http://jsfiddle.net/jasondavis/vp2YN/3/ you can see I need to get the ID attribute of a clicked item and assign it to a variable in Javascript.
Right now the code returns the ID name of the first item, regardless of which item is clicked on.
In the Javascript you can see I have this line commented out...
var clickedID = this.attr("id");
when I use that line, I get an error saying: Object has no method 'attr'
Please help me get the ID name of the clicked link and assign it to a variable
HTML
<a href="#" style="display:block" class="button insertcolumn" id="one_half">2 Columns</a>
<a href="#" style="display:block" class="button insertcolumn" id="one_third">3 Columns</a>
<a href="#" style="display:block" class="button insertcolumn" id="one_fourth">4 Columns</a>
Javascript/jQuery
jQuery('.insertcolumn').click(function(){
var clickedID = jQuery('.insertcolumn').attr("id");
//var clickedID = this.attr("id");
alert(clickedID);
});
Demo http://jsfiddle.net/jasondavis/vp2YN/3/
To get the clicked element, use target property on the event object. Use the id property on the event. target object to get an ID of the clicked element.
Answer: Use the jQuery . attr() Method attr() method to dynamically set or change the value of href attribute of a link or anchor tag. This method can also be used to get the value of any attribute.
Answer: Use the window. location. href Property You can use the JavaScript window. location. href property to get the entire URL of the current page which includes host name, query string, fragment identifier, etc. The following example will display the current url of the page on click of the button.
You have to reference the one you clicked with the jQuery wrapper!
You want to use
$(this).attr('id');
To get the id (without traversing the DOM for no reason) you would be better off to just call the object id
.
this.id;
But to access the property regardless of the type of attribute and depending on the name of the attribute use the following code.
jQuery('.insertcolumn').click(function(){
var clickedID = $(this).attr('id');
alert(clickedID);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With