Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery selector .each()

Tags:

jquery

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 button is pressed, I want to make 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').each function, $(this) isn't the p element. I am missing something here. How can I iterate in all p and find the first a element?

And am I construction the object correctly? I mean if I pass it to a php page, will it json_decode correctly?

thanks

like image 676
Harris Avatar asked Dec 21 '22 16:12

Harris


2 Answers

try find() instead of first():

links[index] = $(this).find('a').attr('href');

first has no selector parameter

like image 194
felixsigl Avatar answered Jan 03 '23 14:01

felixsigl


Try this:

  $('#myfavorites p').each(function(key,value) {
    links[key] = $(value).first('a').attr('href');
  });

jquery each docs: http://api.jquery.com/jQuery.each/

like image 24
VMOrtega Avatar answered Jan 03 '23 14:01

VMOrtega