George Gervin
George Gervin

Reputation: 235

How to get innerhtml of child span of element by ID javascript

Here is my html, I need to get the innerhtml value of the span class that is a child of a div class.

<div id="id1" class="topdiv" entity="id1">
    <div class="topmiddiv">
        <p class="topmiddiv">
            <span class="topmiddiv">Text Here</span>

My first thought was the JS I have below but the span class I am looking for does not always have the same index. Is there any way to get the first span child?

document.getElementById("id1").childNodes[2].innerHTML

Upvotes: 2

Views: 8841

Answers (3)

Tushar
Tushar

Reputation: 87203

As you're using jQuery.

$('#id1 span.topmiddiv').html()

This will find the <span> having class topmiddiv element inside #id1 and return its innerHTML.

Demo:

alert($('#id1 span.topmiddiv').html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="id1" class="topdiv" entity="id1">
  <div class="topmiddiv">
    <p class="topmiddiv">
      <span class="topmiddiv">Text Here</span>
    </p>
  </div>
</div>

Using Vanilla Javascript, you can use querySelector.

alert(document.querySelector('#id1 span.topmiddiv').innerHTML);
<div id="id1" class="topdiv" entity="id1">
  <div class="topmiddiv">
    <p class="topmiddiv">
      <span class="topmiddiv">Text Here</span>
    </p>
  </div>
</div>

Upvotes: 3

Robin
Robin

Reputation: 471

Kindly use this as your selector :

$("span.topmiddiv").html();

Upvotes: 0

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123377

You may use vanilla JS for this task

document.querySelectorAll('#id1 span.topmiddiv')[0].innerHTML;

Upvotes: 5

Related Questions