YuDroid
YuDroid

Reputation: 1639

How to get value of Paragraph element contained in <div> in HTML using JavaScript

I know this can be very basic but I'm very poor in using JavaScript.

Following is my HTML Code :

<div class="request">
<h4>Request a Free Consultation</h4>
<p>XXX-XXX-XXXX</p>     
</div>

Using JavaScript, I want to get text contained in <p> element.

I am trying in the following way, but it's giving me undefined error.

var x = document.getElementsByClassName("request");
var pText = x.getElementsByTagName("P").innerHTML;
alert(pText);

Can anyone lead me in the right direction?

EDIT : Here is the fiddle link to try above code : http://jsfiddle.net/Scoobler/ua9zN/

Upvotes: 1

Views: 3896

Answers (3)

Amit Joki
Amit Joki

Reputation: 59232

var x = document.getElementsByClassName("request");

The above line returns NodeList. It's like an Array, whose elements can be retrieved using the index. getElementsByTagName too returns the same.

for(var i = 0; i < x.length; i++)
  alert(x[i].getElementByTagsName('p')[0].innerHTML); // [0] to get <p>

Upvotes: 0

Etheryte
Etheryte

Reputation: 25310

You can simply use querySelectorAll.

var pText = document.querySelectorAll('.request p')[0];

Upvotes: 1

antyrat
antyrat

Reputation: 27765

getElementsByClassName and getElementsByTagName return arrays. So you need to add indexes as well:

var x = document.getElementsByClassName("request");
var pText = x[0].getElementsByTagName("P")[0].innerHTML;
              ^                            ^
alert(pText);

Upvotes: 3

Related Questions