-1

Hello how can i loop through ul li elements and get the text content only from the li, excepting the text content of its children?

<li class="lom">@paul<div class="on-off">offline</div></li>
<li class="lom">@alex<div class="on-off">offline</div></li>
<li class="lom">@jhon<div class="on-off">offline</div></li>

I want to get only the @paul without offline, I have tried this:

var lnx = $('.cht(ul class) .lom');
for (let i = 0; i < lnx.length; i++) {
    var txt = lnx[i].textContent;
    console.log(txt + '\n');
}

But i get @pauloffline

Paul Taran
  • 34
  • 5
  • If you control the structure of the html, wrapping the first text node in a `` would make it simpler to target it's textContent. Or put that value in a `data-` attribute also – charlietfl Apr 28 '21 at 00:28
  • `@pauloffline`? Never pollute names with logic data. An object like `{name: "@paul", status: "offline"}` is a much better data. – Roko C. Buljan Apr 28 '21 at 00:36
  • Possible duplicate of: https://stackoverflow.com/a/11348383/383904 which can be used like: `$(iteratingLIElement).ignore(".on-off").text(); // @paul` – Roko C. Buljan Apr 28 '21 at 00:40

3 Answers3

1

Iterate through the .childNodes, filtering by nodeType of 3 (text node), to get only nodes that are text node children:

const texts = [...document.querySelector('.lom').childNodes]
  .filter(node => node.nodeType === 3)
  .map(node => node.textContent)
  .join('');
console.log(texts);
<ul>
<li class="lom">@paul<div class="on-off">offline</div></li>
</ul>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • but document.querySelectorAll.childNodes is not iterable – Paul Taran Apr 28 '21 at 00:27
  • `querySelectorAll` is a *function*, you must call it. Then, with each `
  • ` you're iterating over, use the code in my answer, substituting the `
  • ` you want to iterate over. `.childNodes` is not a property of the `querySelectorAll` function
  • – CertainPerformance Apr 28 '21 at 00:34