如何从LI获取H3标签的内容

时间:2015-06-08 14:23:27

标签: javascript jquery html

我有一个包含一堆li的列表。我需要遍历这些li并在h3中获取文本,在下面的html中它表示社区。

例如,我可以像这样循环通过li:

$('#subpanel_list li').each(function(){
    console.log($(this).closest('div').children('table').children('h3').html());
}); 

但我无法获得价值Community。如何使用jQuery从li内部的html中获取该值?

<li class="noBullet" id="whole_subpanel_accounts_accounts_1">
    <div id="subpanel_title_accounts_accounts_1" onmouseover="this.style.cursor = 'move';" style="cursor: move;">
        <table width="100%" cellpadding="0" cellspacing="0" border="0" class="formHeader h3Row">
            <tbody>
                <tr>
                    <td nowrap="">
                        <h3>
                            <span>
                                <a name="accounts_accounts_1"/>
                                    <span id="show_link_accounts_accounts_1" style="display: none;">
                                        <span id="hide_link_accounts_accounts_1" style="">
                                            Community
                                        </span>
                        </h3>
                    </td>
                    <td width="100%">
                </tr>
            </tbody>
        </table>
    </div>
    <div cookie_name="accounts_accounts_1_v" id="subpanel_accounts_accounts_1" style="">
</li>

3 个答案:

答案 0 :(得分:2)

如果您只想要文字,请使用text()而不是html()。 h3是li的后代,所以使用最接近的是错误的。最接近的是相反的方向,所以你看着祖先。您需要使用find()

$(this).find("h3").text()

答案 1 :(得分:2)

closest()上升到DOM树,而你似乎想要下去它。请尝试使用find()

$('#subpanel_list li').each(function(){
    console.log($(this).find('div').children('table').children('h3').html());
}); 

请注意,您也可以将此选择器缩短为单个find()

$(this).find('div table h3').html()

您也可以更好地使用text()方法而不是html(),因为您声明只需要Community值,而不是编码的HTML。

最后,您似乎有几个未公开的HTML元素,但我认为这只是在转录问题示例时的问题。

答案 2 :(得分:0)

find()而不是closest(),您可以简化链式children()

$(this).find('div > table h3').html()