Reputation: 7
I am generating html list items from a Json. The ID is equal to its ID in the JSON. So I can not specifically refer to id='thing'. Question is, how do I, in later functions, get the function to refer to the id of the object when I only know what id = i?
html += "<li class='list-item ui-state-default addNewContext' id=" + i + ">" + card.card_name + ' - ' + card.price + "<button> X </button>" + "</li>" ; /
Upvotes: 0
Views: 187
Reputation: 869
if you're using jQuery you could also reference its position in the list (assuming i doesnt increment by 1)
$('.list-item:eq(0)').text()
Where :eq(#)
is the location of the item in the list
If the function is being referenced within the generated list item you could also try navigating up the dom with jQuery's parent() functions: https://api.jquery.com/parent/
Upvotes: 0
Reputation: 470
The real question is how you are adding your variable html
to your DOM. Using jQuery's .html()
, the id thing
will accessible via $('#thing')
. Working example.
Upvotes: 0
Reputation: 1774
First of all your code is wrong. You should wrap id
with single quotes in your code because of id=1
means nothing to browser but id='1'
does.
html += "<li class='list-item ui-state-default addNewContext' id='" + i + "'>" + card.card_name + ' - ' + card.price + "<button> X </button>" + "</li>" ;
You can access this element by :
document.getElementById(id)
or in jQuery :
$("#" + id)
Upvotes: 0
Reputation: 4084
If you want id of your list you can do like this.
var x = $(".addNewContext"); // class on list
var id = x.attr("id");
Upvotes: 0
Reputation: 3020
You already have the i
which is the id. Do you mean you want a reference to the element with that id?
var myObj = jQuery("#" + i);
Upvotes: 1