How to get html from element by id with jQuery

青春壹個敷衍的年華 提交于 2019-12-07 03:30:46

问题


I have simple list:

<ul id="tabs_nav">
    <li id="t_00">data</li>
    <li id="t_01">data</li>
    <li id="t_02">data</li>
    <li id="t_03">data</li>
</ul>

Now: How do I get the html of the first element, depending on what is ID. I would add that all of ID's change dynamically with the click of the button. This is my code:

btn.on('click',function(){
    var ladder_nav_tabs = $('#tabs_nav'),
        first_ladder_element_inset_id = ladder_nav_tabs.find('li').first().attr('id'),
        first_ladder_element_inset_html = ladder_nav_tabs.find(first_ladder_element_inset_id).html();
    console.log(first_ladder_element_inset_html);
});

Thx for help.


回答1:


Seems you are missing the id selector #.

You are trying to get the html from the selector:

ladder_nav_tabs.find(first_ladder_element_inset_id).html();

This won't work as an id selector needs the #. Like this:

ladder_nav_tabs.find("#" + first_ladder_element_inset_id).html();

Try the following to fix your code:

btn.on('click',function(){
    var ladder_nav_tabs = $('#tabs_nav'),
        first_ladder_element_inset_id = ladder_nav_tabs.find('li').first().attr('id'),
        first_ladder_element_inset_html = ladder_nav_tabs.find("#" + first_ladder_element_inset_id).html();
    console.log(first_ladder_element_inset_html);
});

DEMO - Updating to valid id selector syntax


Alternatively you could shorten your code using jQuery's eq, similar to this:

btn.on('click',function(){
    var theHtml = $('#tabs_nav li').eq(0).html();
    console.log(theHTML);
});



回答2:


Don't use jQuery purely as a selector engine:

btn.onclick = function() {
  console.log(document.getElementById('tabs_nav').children[0].innerHTML);
};



回答3:


Check out the jQuery first-child selector. Specifically:

btn.on('click',function(){
    var first_child = $('#tabs_nav li:first-child');
    var first_child_html = first_child.html();
}); 



回答4:


Try this:

btn.on('click',function(){
    var ladder_nav_tabs = $('#tabs_nav'),
        first_ladder_element_inset_id = ladder_nav_tabs.find('li:first-child').attr('id'),
        first_ladder_element_inset_html = ladder_nav_tabs.find(first_ladder_element_inset_id).html();
    console.log(first_ladder_element_inset_html);
});

You have tou use :first-child



来源:https://stackoverflow.com/questions/14593727/how-to-get-html-from-element-by-id-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!