Considering I have this div
:
<div class="ResCheckIn">
<div class="ResDtlLabel">
Check-in
</div>
Thursday, October 18, 2018
</div>
I simply want to get the string "Thursday, October 18, 2018"
, so excluding the inner div
.
If I try with .innerHMTML
:
document.querySelectorAll('.ResCheckIn').innerHTML;
It returns everything in .ResCheckIn
, including the inner div
with class "ResDtlLabel"
, so this:
<div class="ResDtlLabel tSmall tLight">
Check-in</div>
Thursday, October 11, 2018
And ideally I would love to do that without using jQuery.
Using loops with appendChild() seems to be the fastest way to insert new HTML content. But its advantage over innerHTML is absolutely insignificant when rendering time is considered — compare 92–83=9 ms with 1500 ms. So it is fare to say that both methods are equally performant.
innerText returns all text contained by an element and all its child elements. innerHtml returns all text, including html tags, that is contained by an element.
Should I use innerHTML or createElement? #1) createElement is more performant However, using the innerHTML causes the web browsers to reparse and recreate all DOM nodes inside the div element. Therefore, it is less efficient than creating a new element and appending to the div.
One option is iterating through childNodes
and filtering the textNodes
. The following function gets all the textNode
children and stores their values in an array.
const nodes = document.querySelector('.ResCheckIn').childNodes;
const texts = [].reduce.call(nodes, function(ret, el) {
if ( el.nodeType === 3 ) {
ret.push(el.nodeValue.trim());
}
return ret;
}, []);
texts
is an array of textNode
s contents.
Not a very innovative answer but if you are looking for simple solution try this
var content = document.querySelector(".ResCheckIn").innerHTML;
content = content.split('</div>');
if(content[1]){
content = content[1].trim();
}
You can use like this:
document.querySelectorAll('.ResCheckIn')[0].textContent
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With