How to find particular label value inside div tag using jQuery

15,716

Solution 1

Try # id-selector

$('#redLabel').text();

or

$('#redLabel').html();


$('#redLabel') -->refers to element with id redLabel

$('#redLabel').text(); --> get text of element with id redLabel

$('#redLabel').text('value'); --> set text of element with id redLabel


.text()

.html()


ID must be unique. Use classes for multiple items or refer to a group

Read Two HTML elements with same id attribute: How bad is it really?

Solution 2

try this

 $("#myDiv #redLabel").text();
  //go to div then label
 // or can try if in label there is no element
     $("#myDiv #redLabel").html();

you can also use $("#redLabel") at the place of $("#myDiv #redLabel")

see also What is the difference between jQuery: text() and html() ?

Share:
15,716
Dhaval Panchal
Author by

Dhaval Panchal

Updated on July 25, 2022

Comments

  • Dhaval Panchal
    Dhaval Panchal almost 2 years

    I need to read the value of particular label inside the div tag using jQuery. Below is the HTML structure.

    <div id="myDiv">
    <label id="greenLabel">Hello</label>
    <label id="redLabel">There you go!</label>
    </div>
    

    Can anyone help me to find the inner text of "redLabel" ?

  • Dhaval Panchal
    Dhaval Panchal over 10 years
    writing directly "$('#redLabel').text();" reads all the labels in the page. I want to read it from particular div tag.
  • DaniP
    DaniP over 10 years
    @DhavalPanchal that read only label for ID redLabel and if ID are uniques then you get only one value.
  • Dhaval Panchal
    Dhaval Panchal over 10 years
    Yes - ID is unique. I have ASP.Net label within DIV and set ClientIDMode="static". So, It renders HTML as mentioned in Question.
  • Tushar Gupta - curioustushar
    Tushar Gupta - curioustushar over 10 years
    @DhavalPanchal if id is unique it must select only one label .
  • Dhaval Panchal
    Dhaval Panchal over 10 years
    ID is unique within that div tag. But in page there are too many labels with the same name.
  • Tushar Gupta - curioustushar
    Tushar Gupta - curioustushar over 10 years
    @DhavalPanchal label id's also must be unique or you can use class instead for all labels .