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

+4
source share
3 answers

try find() instead of first() :

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

doesn't have a selection option at first

+10
source

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/

0
source

.first() does not work. It takes a selector and returns the 1st from the list and takes no arguments.

 $('a', this).first().attr('href'); 

Or you can use the :first selector.

 $('a:first', this).attr('href'); 
0
source

Source: https://habr.com/ru/post/1343777/


All Articles