Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get html from element by id with jQuery

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.

like image 352
Lukas Avatar asked Jan 29 '13 23:01

Lukas


People also ask

How do you select element by id in jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.

How do I get all HTML elements in jQuery?

To get HTML content of an element using jQuery, use the html() method. The html() method gets the html contents of the first matched element.

What is $() in jQuery?

In the first formulation listed above, jQuery() — which can also be written as $() — searches through the DOM for any elements that match the provided selector and creates a new jQuery object that references these elements: 1. $( "div.


2 Answers

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);
});
like image 194
Nope Avatar answered Sep 29 '22 07:09

Nope


Don't use jQuery purely as a selector engine:

btn.onclick = function() {
  console.log(document.getElementById('tabs_nav').children[0].innerHTML);
};
like image 40
Niet the Dark Absol Avatar answered Sep 29 '22 07:09

Niet the Dark Absol