This might be a duplicate but I can not find a solution for the small challenge I am facing. I want to assign the href and text in an <a>
tag to variables and use them in a jquery script. Examples I have found pertain to diving into the DOM and retrieving several <a>
based on class or specific ones based on an id. I think there should be a way to drill down and select a particular one.
I have a list of links rendered from php. Currently, they all have the same class. An admin user has the option of editing or deleting the link. These editing and deleting options are carried out with jquery and ajax. Below is how any of the links is coded. (Formatted for simple presentation here.)
<ul class="url_list">
<li>
<input type="hidden" value="95" name="id">
<a href="http://www.foo.com/index.html" target="blank">See this</a>
<span class="itemDelete">
<img alt="Delete this link" title="Delete this link"
src="images/ajax-urls/deleteIcon.png">
</span>
<span class="itemEdit">
<img alt="Edit this link" title="Edit this link"
src="/images/ajax-urls/editIcon.png">
</span>
</li>
</ul>
The hidden field with a numeric value is to be used for deleting a url from the database.
This is my javascript:
$(document).on('click', '.itemEdit', function() {
var url_id = $('input[name="id"]').val();
var recipie_id = $('input[name="recipe_id"]').val();
var href = $(this).closest('a').attr('href');
... more code
});
I also tried:
$(document).on('click', '.itemEdit', function(e) {
var url_id = $('input[name="id"]').val();
var recipie_id = $('input[name="recipe_id"]').val();
var href = $(e.target).closest('a').attr('href');
... more code
});
I can't figure out how to assign href
to a variable. Stepping through the code or echoing out href
to the console and href
comes up empty. Keep in mind, it is the <a>
closest to <span class="itemEdit">
that I want.
Thank you for taking the time to read this.