I have the following code with Jquery.
JavaScript
x
7
1
var myHTML = $(`<a href="/wiki/Indian_Rebellion_of_1857" title="Indian Rebellion of 1857">Indian Rebellion of 1857</a>: Indian rebels seize Delhi from the British.<sup id="cite_ref-11" class="reference"><a href="#cite_note-11">[11]</a></sup>`)
2
var firstLinkText = myHTML.find("a:first").text()
3
4
console.log(firstLinkText)
5
6
// Output "[11]"
7
I don’t know why the first link <a>
is not getting selected but the last one? Anything wrong in my code, any fix?
JavaScript
1
7
1
var html = `<a href="/wiki/Indian_Rebellion_of_1857" title="Indian Rebellion of 1857">Indian Rebellion of 1857</a>: Indian rebels seize Delhi from the British.<sup id="cite_ref-11" class="reference"><a href="#cite_note-11">[11]</a></sup>`
2
var myHTML = $(html)
3
4
var firstLinkText = myHTML.find("a:first").text()
5
console.log(firstLinkText)
6
document.body.textContent = (html)
7
document.write("<br><br>Output: " + firstLinkText)
JavaScript
1
1
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Advertisement
Answer
The issue is because by using find()
you’re telling jQuery to look for the selector you provide within the parent element. As the parent itself is the a
element, it obviously doesn’t find anything.
To fix this you can instead use filter()
:
JavaScript
1
4
1
var $myHTML = $(`<a href="/wiki/Indian_Rebellion_of_1857" title="Indian Rebellion of 1857">Indian Rebellion of 1857</a>: Indian rebels seize Delhi from the British.<sup id="cite_ref-11" class="reference"><a href="#cite_note-11">[11]</a></sup>`)
2
var firstLinkText = $myHTML.filter('a:first').text()
3
4
console.log(firstLinkText)
JavaScript
1
1
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>