简体   繁体   中英

how to find the id of html element that is generated from json

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>" ; /

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);

If you want id of your list you can do like this.

var x = $(".addNewContext"); // class on list 

var id = x.attr("id");

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)

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 .

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM