satyajit
satyajit

Reputation: 1570

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.

Upvotes: 9

Views: 38342

Answers (4)

Mohsin Shoukat
Mohsin Shoukat

Reputation: 1250

here is your paragraph element in html or php file which is id assign tt

<p id="tt">ALert Message </p>
in in jquery file to get the text of your paragraph with tt id can be

var tt = $("#tt").text();
alert(tt);

working fine for jquery-3.1.1.js

Upvotes: 0

Jesse Dhillon
Jesse Dhillon

Reputation: 7997

Not sure if this would cause a problem, but you have invalid markup. From "The global structure of an HTML document" by the W3C

Generally, block-level elements may contain inline elements and other block-level elements. Generally, inline elements may contain only data and other inline elements. Inherent in this structural distinction is the idea that block elements create "larger" structures than inline elements.

a elements are supposed to be contained by block elements like p, not the other way around.

Upvotes: 0

jpluijmers
jpluijmers

Reputation: 350

the .html() function retrieves a nodes inner html.

$('.body a p').html();

should do the trick

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630637

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());
});

Upvotes: 15

Related Questions