I want to get all "a" tags from page, get its "href" attribute and check if in this href is text ".pdf". So I get all a
tags into tags
variable, then with each()
function I check every "a" (as a tag
). But code:
if ($(tag).indexOf('.pdf') > 0)
console.log($(tag));
is not working. Why? Why I can't use indexOf
on href
? I tried with search()
function, but it's also not working.
So I thought - ok, there's something wrong with this href
. Lets take it as a text.
But code:
var text = $(tag).text();
console.log(text);
is also not working. Can anybody tell me why?
Code snippet has errors intentionally - to show with what I have a problem.
Thank you in advance.
(function($){ var tags = $('a'); $(tags).each(function() { var tag = $(this).attr('href') if ($(tag).indexOf('.pdf') > 0) console.log($(tag)); var text = $(tag).text(); console.log(text); }); }(jQuery));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <html> <a href="https://www.test.com/example.pdf" target="_blank">Link with ".pdf"</a> <a href="https://www.test.com/" target="_blank">Link without ".pdf"</a> </html>
No need to for the additional $(tag)
when calling indexOf. tag
is a string at that point and you don't need to make it a jQuery object. simply call tag.indexOf('.pdf') > 0
. For strings you can also use tag.includes('.pdf')
or you go for tag.substr(tag.length - 4, 4) === '.pdf'
to make it even more precise.
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.