jQuery get value within child div

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

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

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

    If you need to go into lists, use this:

    jQuery('.first > ul > li:nth-child(6)').text();

    Example code gets the value of the 6th item in a list.

    0 讨论(0)
  • 2021-02-04 02:29

    You want to use children() and text() instead of val(). Although, since what you are selecting has an id (and ids must be unique), you could also simply select based on the id without involving the container element at all.

    The val() method only works on input elements, textareas, and selects -- basically all form elements that contain data. To get the textual contents of a container, you need to use text() (or html(), if you want the mark up as well).

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

    or

    var text_val = $('#first').children('#second_child').text(); // yours, corrected 
    
    0 讨论(0)
  • 2021-02-04 02:29

    you can simply:

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

    as pointed by previous answers. but, since you "need to grab the text value of a child div", i assume that the child div id probably not always available. you can try this instead:

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

    where 1 is the index of the child div (since it count starts from zero)

    0 讨论(0)
  • 2021-02-04 02:30

    ........

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

    For multiple elements with the same id:

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

    For a single element with a particular id:

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

    Try this...

    var text_val = $('#first > #second_child').text();
    
    0 讨论(0)
提交回复
热议问题