Select all HTML elements with text

后端 未结 3 1800
無奈伤痛
無奈伤痛 2021-01-29 06:38

I have HTML document:

Some text

3条回答
  •  生来不讨喜
    2021-01-29 07:18

    You need to get container, then all children, then filter those children. If this is going into a production environment, you'll want to do some error checking and make sure none of those elements return null, undefined or some other bad value.

    var container = document.querySelector('.content'),
        allKids = container.querySelectorAll('*'),
        kidsWithContent = Array.from(allKids).filter(item => item.textContent.length !== 0);
        
    console.log(kidsWithContent);

    Some text

    23.12

提交回复
热议问题