get value of child
of a parent

后端 未结 6 823
面向向阳花
面向向阳花 2021-01-13 06:50
some-value

how do I get \"some-value\"? I tried

<
6条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-13 07:24

    The problem is that parent

    actuially has three children: a TextNode containing a new line after parent opening tag, the actual child
    and yet another TextNode with newline after closing child tag. But hard-coding second item is a bad idea:

    var parent = document.getElementById("parent");
    console.info(parent.childNodes.length);
    var child = parent.childNodes[1];
    var childval = child.innerHTML;
    

    I would suggest iterating over children and finding the actual child or using

    parent.getElementsByTagName('div')
    

    shorthand.

    That's one of the reasons why people love jQuery so much:

    $('#parent div').text()
    

提交回复
热议问题