Nijan
Nijan

Reputation: 93

JavaScript fetching values from div tag

Hi I'm new to JavaScript. I need to fetch value 'KARTHIK' from the following code using document.getElement,

<div class="account-info">
<h3 class="account-header">Welcome back,</h3>
<p>
<strong>KARTHIK</strong><br> 
</p>
</div>

Any one help me in this. Thanks in advance.

Upvotes: 1

Views: 67

Answers (3)

Cooper
Cooper

Reputation: 1

You can use querySelector of document object to get this easily. document.querySelector("div.account-info strong").innerHTML

Refer this jsbin

Upvotes: 0

A.J. Uppal
A.J. Uppal

Reputation: 19264

You can get the element by its tag:

alert(document.getElementsByTagName("strong")[0].innerHTML);
<div class="account-info">
<h3 class="account-header">Welcome back,</h3>
<p>
<strong>KARTHIK</strong><br> 
</p>
</div>

However, get elements by the tag name can be unreliable, because there may be more than one <strong> tag. Thus, it would be advisable to assign an id to the element:

alert(document.getElementById("account-name").innerHTML);
<div class="account-info">
<h3 class="account-header">Welcome back,</h3>
<p>
<strong id="account-name">KARTHIK</strong><br> 
</p>
</div>

Upvotes: 0

Abozanona
Abozanona

Reputation: 2285

You can use innerHTML

you just have to give the strong tag an id.

<strong id="ih">KARTHIK</strong>
<script>var innerStrong=document.getElementById("ih").innerHTML;</script>

Upvotes: 1

Related Questions