Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting text from a paragraph in jquery

This might be a very simple thing in jquery but I am not able to figure it out. My html document has the following structure

 <div class="body"> 
 <a href="/question?id=70"><p>This is the text I want to extract</p></a> 
 </div> 

I tried this

$("body").find("a p").text()

but this does not seem to be working for me. I am able to get the paragraph object but not the text. I tested it with console.log with no use.

like image 835
satyajit Avatar asked Aug 24 '10 00:08

satyajit


People also ask

How do I get text within an element?

Use the textContent property to get the text of an html element, e.g. const text = box. textContent . The textContent property returns the text content of the element and its descendants. If the element is empty, an empty string is returned.

How do I get just the text from HTML in jQuery?

You could use $('. gettext'). text(); in jQuery.

How do I get text inside a div using jQuery?

To get the value of div content in jQuery, use the text() method. The text( ) method gets the combined text contents of all matched elements. This method works for both on XML and XHTML documents.

How do I get text inside a div?

Use the textContent property to get the text of a div element, e.g. const result = element. textContent . The textContent property will return the text content of the div and its descendants. If the element is empty, an empty string is returned.

How do I get text from p tag?

Use the textContent property to get the text of a paragraph element, e.g. const result = p. textContent . The textContent property returns the text content of the p element and its descendants. If the element is empty, an empty string is returned.


1 Answers

What you have should be working (you can test it here), make sure you're running it when the DOM is ready though, like this:

$(function() {
  alert($("body").find("a p").text()); //or just $("a p").text()
});

If it runs earlier, the elements may not be ready, and your selector won't find any matches.

If you want to select the class body make sure to use ".body" instead of "body" (which would select the <body> element). Here's a version using the .class selector:

$(function() {
  alert($(".body a p").text());
});
like image 70
Nick Craver Avatar answered Sep 26 '22 00:09

Nick Craver