Retrieve HTML Span Text and class name in jQuery

amar
 
on Oct 08, 2021 07:15 AM
394 Views

Hi 

How to retrieve the span text and class using Jquery.

I have multiple span under div but I need first span text and sencond span class can anyone help me on button click

sample

<button id="Export" type="button">Export</button>
<div id="mydiv">
    <span>ABC</span>
    <span class="tesxt-abc"></span>
    <span></span>
</div>

 

$('#Export').click(function () {
    var spans = $("#mydiv").find('span');
    for (i = 0; i < spans.length; i++) {
    }
});

when I click button output like below

ABC

tesxt-abc

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Oct 08, 2021 07:21 AM

Hi amar,

Refer below code.

HTML

<html>
<head>
    <title></title>
</head>
<body>
    <button id="Export" type="button">Export </button>
    <div id="mydiv">
        <span>ABC</span>
        <span class="tesxt-abc"></span>
        <span></span>
    </div>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#Export').click(function () {
                var spans = $("#mydiv").find('span');
                var message = $(spans[0]).html() + "\n";
                message += $(spans[1]).attr('class');
                alert(message);
            });
        });
    </script>
</body>
</html>

Demo