Subash
Subash

Reputation: 177

Get the Text inside the element

<p class="MsoNormal" style="margin-bottom:0cm;margin-bottom:.0001pt;text-align:
           justify;line-height:normal">
First Text 

<span lang="EN-US" style="font-size:12.0pt;
            font-family:&quot;Times New Roman&quot;,&quot;serif&quot;">
Second Text</span>

</p>

This is my code, how to get the content inside the paragraph tag. [The tag may change to div or ul]. I need all the content inside the paragraph tag by javascript.

The output should be :

First Text Second Text

Sorry I am new to javascript, searched but cant find answer for this relevant problem. Thanks

Upvotes: 0

Views: 110

Answers (3)

atmd
atmd

Reputation: 7490

To get the value of a tag, you can get the element with a selector and use innerHTML to get the value. like this:

<p>hi there</p>

console.log(document.getElementsByTagName('p')[0].innerHTML);

n.b. in the code above it's selecting by tag name, so it returns an array of matching elements

So in your example, using .innerHTML with give you the P tags content, including any html tags etc.

if you want just the content, you can use .textContent

console.log(document.getElementsByTagName('p')[0].textContent); This wont give you the inner html tags

n.b. there is also the innerText method, However this isnt supported accross browsers.

Upvotes: 2

Huy Hoang Pham
Huy Hoang Pham

Reputation: 4147

InnerText should be a good solution.

console.log(document.getElementsByTagName('p')[0].innerText);
<p class="MsoNormal" style="margin-bottom:0cm;margin-bottom:.0001pt;text-align:
           justify;line-height:normal">
First Text 

<span lang="EN-US" style="font-size:12.0pt;
            font-family:&quot;Times New Roman&quot;,&quot;serif&quot;">
Second Text</span>

</p>

Upvotes: 0

Omri Aharon
Omri Aharon

Reputation: 17064

You can change according to the tag you need, but basically this will do the trick:

document.getElementsByTagName('p')[0].innerText

Fiddle

Upvotes: 0

Related Questions