Search code examples
jquerytext-extractiondom-traversal

How to create array in JQuery using DOM extracted text values


Using JQuery, I want to create an array such as [TextA, TextB, ... Text I]. These array elements are to be extracted from the html code similar to shown below. I'm beginner in this field and tried extrating single text value using:

$('a.curT',$( this )).text();

"But its not working" as I am no getting "Text E" as the desired output. Also I don't have idea how to create an array using the extracted values.

<li class="top1">
<a class="tc1" href="link" title="title">Some Text</a>
<div class="top2 current">
    <div class="column" style="width:25%">
        <ul>    
            <li class="class1"><a href="linkA" title="A"><strong>Text A</strong></a></li>
            <li class="class1"><a href="linkB" title="B"><strong>Text B</strong></a></li>
            <li class="class1"><a href="linkC" title="C"><strong>Text C</strong></a></li>    
        </ul>
    </div>                    
    <div class="column" style="width:25%">
        <ul>    
            <li class="class1"><a href="linkD" title="D"><strong>Text D</strong></a></li>
            <li class="class2"><a href="linkE" title="E" class="curT"><strong>Text E</strong></a></li>
            <li class="class1"><a href="linkF" title="F"><strong>Text F</strong></a></li>
        </ul>
    </div> 
    <div class="column" style="width:25%">
        <ul>    
            <li class="class1"><a href="linkG" title="G"><strong>Text G</strong></a></li>
            <li class="class1"><a href="linkH" title="H"><strong>Text H</strong></a></li>    
        </ul>
    </div>    
    <div class="column" style="width:25%">
        <ul>    
            <li class="class1"><a href="linkI" title="I"><strong>Text I</strong></a></li> 
        </ul>
    </div>
</div>

Any suggstion in this direction will be very helpful. Thank you.


Solution

  • You can use map() to project an array from matched elements:

    var textArray = $("li a strong").map(function() {
        return $(this).text();
    }).get();