I have a page* with several .article
divs with the following markup:
<div class="article">
<div class="featured-img">
<a href="https://www.johornow.com/english/things-to-do-at-kota-tinggi/" style="background: none;">
</a>
</div>
<div class="featured-info">
<h3 class="article-title">
<a href="https://www.johornow.com/english/things-to-do-at-kota-tinggi/">Fun Things to Do and Amazing Places to Visit at Kota Tinggi</a>
</h3>
</div>
</div>
Now I want to get all the anchor links:
$('.article').each( e => $(this).find('article-title').find('a').attr("href") )
Surprisingly I failed to do so, I got DOM node. What's wrong with my code?!
There are couple of errors in your code:
1) JQuery is all about chaining, that's why functions like each
return the initial set and not the elements you return in the function (or a collection of your return values?). What you want/need here is .map
.
2) your find was missing the .
for addressing a class. Also, you can write it in a single statement find(".article-title a")
.
3) Fat arrow functions don't establish their own context, thus $(this)
won't work. Instead you have to use the "old-school" way of writing functions, to actually have this
refer to the single elements.
The following jquery solution
$('.article .article-title a').map( function(){return console.log($(this).attr("href"))} )
creates an array with all the link hrefs.
So does the following vanilla JS (which I actually always prefer):
[].map.call(document.querySelectorAll('.article .article-title a'), e=>e.href )
There you have your fancy fat arrow again - also, it's shorter, (possibly faster) and does not rely on third-party;)
You can get all the links in an array
var m =[];
$('.article').each(function(e,v){
m.push($(this).find('h3 > a').attr("href"))
})
console.log(m)
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.