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
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>
Here's a jQuery variant that uses the .ignore() micro plugin
$.fn.ignore = function(sel) { return this.clone().find(sel||">*").remove().end(); }; // Get LI element by text const $userLI = (text) => $(".lom").filter((i, el) => $(el).ignore().text().trim() === text); // Use like $userLI("@paul").css({color: "gold"});
<ul> <li class="lom">@paul <span class="on-off">offline</span></li> <li class="lom">@alex <span class="on-off">offline</span></li> <li class="lom">@jhon <span class="on-off">offline</span></li> <li class="lom">@paul</li> </ul> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Jquery solution using replace
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/String/replace
$('.lom').each(function(index, value) { var getContent = $(this).text(); var replaceTxt = getContent.replace('<div class="on-off">offline</div>','').replace('offline',''); //$(this).find('.on-off').remove(); if (replaceTxt == '@paul') { console.log(replaceTxt); } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.