Skip to content
Advertisement

Get all innerhtml contents of span tags

I am trying to get the content of all span tags that are children of div#parent and I am not able to do it, I just get the first one. Could someone help me, please!

$( document ).ready(function() {
    var allspans=$("#parent").find("span").html();
    console.log( allspans );
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>jQuery</title>
</head>
<body>
  <div id="parent">
    <span>Element_1</span>
    <span>Element_2</span>
    <span>Element_3</span>
    <span>Element_4</span>
    <span>Element_5</span>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
  </div>
</body>
</html>

Thank you! Best Regards!

Advertisement

Answer

Try with map() and get() function .You will get the all the span tag innerHTML with in array

$( document ).ready(function() {
    var allspans=$("#parent").find("span").map(function(){
    return $(this).html();
    }).get()
    console.log( allspans );
});
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>jQuery</title>
</head>
<body>
  <div id="parent">
    <span>Element_1</span>
    <span>Element_2</span>
    <span>Element_3</span>
    <span>Element_4</span>
    <span>Element_5</span>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
  </div>
</body>
</html>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement