jQuery get value within child div

后端 未结 8 1683
没有蜡笔的小新
没有蜡笔的小新 2021-02-04 01:50

I need to grab the text value of a child div.

A
B
相关标签:
8条回答
  • 2021-02-04 02:45

    next() and nextAll() traverse the siblings of the element, not the children. Instead, use "find()"

    var text_val = $('#first').find('#second_child').html();
    

    You use val() when dealing with elements like inputs and textareas. html() will return whatever is under the div (which works in your example). text() will return the text in the element (wich would also work in your example).

    Your example also makes me suspicious of your design. If you have multiple ids set to "#second_child", your html is confused. Instead, use a class. However, if there's only one id "#second_child", then all you need is:

    var text_val = $('#second_child').text();
    
    0 讨论(0)
  • 2021-02-04 02:53

    Simple,

    var text_val = $('#second_child').text();
    

    Or your change,

    var text_val = $('#first').children('#second_child').text();
    

    This will return "B" from div of id "second_child"

    UPDATE Changed the second solution to children() instead of nextAll().

    0 讨论(0)
提交回复
热议问题