简体   繁体   中英

Select all innerHTML of td in ul li hierarchy

I have an html structure as follows-

<ul id='abc'>
    <li>
        <table>
            <tbody>
                <tr>
                    <td>
                        A
                    </td>
                </tr>
            </tbody>
        </table>
    </li>
    <li>
        <table>
            <tbody>
                <tr>
                    <td>
                        B
                    </td>
                </tr>
            </tbody>
        </table>
    </li>       
    ...
    ...
</ul>

I want to store A,B,C... values in an array using jquery.Please help...

You can use $.fn.map()

Translate all items in an array or object to new array of items.

var arr = $('#abc td').map(function(){
    return $(this).text();
}).get();

you can do this by javascript by The

Element.getElementsByTagName() method returns a live HTMLCollection of elements with the given tag name

var values = []
var tableUl = document.getElementById("abc"); 
var cells = tableUl.getElementsByTagName("td"); 
for (var i = 0; i < cells.length; i++) { 
    values.push( cells[i].textContent.trim()); 

}

fiddle

Here is what you want:

var values = [];
$('ul li').find('td').each(function() {
  values.push($(this).html());
});

这应该工作:

var values = $('ul#abc td').map(function() { return $(this).text(); });

Try utilizing .text() , String.prototype.match()

 var res = $("#abc td").text().match(/\\w+/gi) console.log(res) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script> <ul id='abc'> <li> <table> <tbody> <tr> <td> A </td> </tr> </tbody> </table> </li> <li> <table> <tbody> <tr> <td> B </td> </tr> </tbody> </table> </li> </ul> 

Another way would be:

$("ul#abc li td:first-child").each(function () {
   //alert($(this).text());
   console.log($(this).text());
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM