I want to retrieve span title in the following html.
<div id="header_customerid_d">
<div>
<span title="This is my span"></span>
</div>
</div>
I have tried with following jquery bt i got "undefined" alert.
var CustomerId = $('#header_customerid_d',this开发者_开发知识库).children("div").children("span").attr("title");
alert(CustomerId);
So please provide me with correct solution.
Thanks, Bharat Mhatre
var CustomerId = $("#header_customerid_d span").prop("title");
should do the trick. See an example fiddle here.
Note that the prop
function is only available in jQuery 1.6+. If you are using an older version of jQuery, use attr
instead:
$("#header_customerid_d span").attr("title");
Assuming that you are not used to working with id
, you can always assume the "order".
$('span')[0]
This bit of code gives you the first span
element that you are interested in. But if I modify your code a tiny bit:
<div id="header_customerid_d">
<div>
<span id="sp_1" title="This is my span"></span>
</div>
</div>
Look at the id
in the span that makes an easier jQuery:
$('#sp_1')[0].title
will return the title of the span that you are interested in. There are lots of jQuery tutorial on the web, but almost all of them recommends that you put an id
for each of your HTML elements. It's your friend.
So, the code becomes:
var CustomerId = $('#sp_1')[0].title;
alert(CustomerId);
Of course, you might come back and say "Ey I don't have control over assignment of `id' attributes to all of my HTML documents, please give me something else!". In that case,
$('#header_customerid_d').children("div").children("span")[0].title
Should give you the title
attribute. You can also use it is getter and setter i.e.
$('#header_customerid_d').children("div").children("span")[0].title = "blablabla"
will set the title to "blablabla".
Try:
$('div#header_customerid_d').find("span").attr("title");
See Here
And if there are multiple spans in div then you have to use jQuery.each() to get each.
You don't need, or want to include this
in your jQuery selector call.
Change your code to this:
var CustomerId = $('#header_customerid_d').children("div").children("span").attr("title");
alert(CustomerId);
and it will work.
Or, if you want to be more concise, do as one of these other fine gentlefolk have suggested!
ian.
精彩评论