Jquery.each () selector
Consider the following HTML:
<div id="myfavorites"> <p><button id="saveFav">Save my favorites</button> </p> <p><a href="http://bit.ly/fzgxya">http://bit.ly/fzgxya</a> <a class="favlinks" href="#">(remove me)</a></p> </div> When the button is pressed, I want to create a json object with all the links.
$('#saveFav').click(function() { var toSave = { "searchtext" : $('#searchText').val().trim() }; var links = {}; $('#myfavorites p').each(function(index) { links[index] = $(this).first('a').attr('href'); }); toSave.links = links; } But in $ ('# myfavorites p') every function, $ (this) is not an element of p . Something is missing for me. How can I iterate over all p and find the first element of a ?
And did I build the object correctly? I mean, if I pass it to a php page, will it be json_decode right?
thanks
Try the following:
$('#myfavorites p').each(function(key,value) { links[key] = $(value).first('a').attr('href'); }); jquery each docs: http://api.jquery.com/jQuery.each/