Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript .innerHTML but excluding inner div

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.

like image 476
Alessandro Crotti Avatar asked Sep 19 '18 11:09

Alessandro Crotti


People also ask

Is appendChild faster than innerHTML?

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.

Should I use innerHTML or innerText?

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?

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.


3 Answers

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 textNodes contents.

like image 60
undefined Avatar answered Sep 20 '22 14:09

undefined


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();
    }
like image 43
Pawnesh Kumar Avatar answered Sep 21 '22 14:09

Pawnesh Kumar


You can use like this:

document.querySelectorAll('.ResCheckIn')[0].textContent
like image 41
Rajeev Avatar answered Sep 20 '22 14:09

Rajeev