0

With the selector $('div.alert') I get the following:

<div class="alert alert-success alert-dismissible fade show" role="alert">
<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
Foo Bar is now locked
</div>

I want to return the text Foo Bar is now locked. But using $('div.alert').text() all I get is ...text() is not a function. How to retrieve the text?

geoB
  • 4,578
  • 5
  • 37
  • 70
  • 1
    The error you describe `text() is not a function` should not occur. Can you make a live example with a Stack Snippet? I think you've copied something wrong from the code you're actually using – CertainPerformance Feb 21 '22 at 15:02
  • This means `$` does not refer to jQuery constructor. Try with running `jQuery(...).text()` instead. – Ram Feb 21 '22 at 15:05
  • Or `$` is not jquery and defined as something else, eg if you're using it in the console, most browsers have `$` defined – freedomn-m Feb 21 '22 at 15:05
  • 2
    Possibly related, but you're not getting `$` is not defined, but might help: [jquery is not defined](https://stackoverflow.com/questions/2194992/jquery-is-not-defined) – freedomn-m Feb 21 '22 at 15:07
  • 2
    Seems like an XY problem (.text is not a function) but to answer your actual question: you can get the text (without the button) using: `$("div.alert").contents().filter(function() { return this.nodeType == 3; })[0].nodeValue` As provided by [this answer](https://stackoverflow.com/a/14755309/2181514) – freedomn-m Feb 21 '22 at 15:12
  • Please check jquery, to do so, add to your js (just before your error line): `console.log(jQuery.fn.jquery); console.log($.fn.jquery)` - please let us know the result. – freedomn-m Feb 21 '22 at 15:14
  • @freedomn-m I did not know that "... most browsers have $ defined". Which gives me other directions to go. But my ignorance got a downvote. Hadn't realized that ignorance was to be penalized either. – geoB Feb 21 '22 at 16:57
  • To clarify, most browsers have `$` defined *in the console* - more info on `$()` and `$$()` on [this answer](https://stackoverflow.com/a/35682911/2181514). These are not available/defined on your page. Looks like you do have the [$ is not defined](https://stackoverflow.com/questions/2194992/jquery-is-not-defined) issue. – freedomn-m Feb 21 '22 at 17:01
  • 1
    Many thanks for your comments. The context of the question was to determine a selector to use with Symfony's DomCrawler. I had made the erroneous assumption that I'd already defined jQuery some time ago. So, while more tedious, I'll work within the DomCrawler. – geoB Feb 21 '22 at 18:18

0 Answers0