Как получить div из тега в js, если внутри div, есть теги span, с своим текстом? <div> <div class='qt'> <span class="text1">этот не нужно получать<span class="text2">и этот тоже</span></span> А этот нужно получить. </div> </div> 

Attempt:

 var $qtext = document.body.getElementsByClassName('qt'); var $question = $qtext[0].parentNode.getElementsByTagName('div'); console.log("Текст " + $question[0].innerText); 
 <div> <div class='qt'> <span class="text1">этот не нужно получать<span class="text2">и этот тоже</span></span> А этот нужно получить. </div> </div> 

  • will do? stackoverflow.com/a/6925135/6104996 - Alexey Shimansky
  • If it is pure on js then var qt = document.getElementsByClassName("qt")[0]; alert(qt.childNodes[2].textContent) var qt = document.getElementsByClassName("qt")[0]; alert(qt.childNodes[2].textContent) - Aleksey Shimansky
  • @ Alexey Shimansky Thank you very much. It also works. Do you often write on js, or more on jQuery? - gilo1212

2 answers 2

It is possible to operate in the old manner with DOM nodes. For example:

 var qt = document.querySelector('.qt'), children = qt.childNodes, value = children[children.length - 1].nodeValue.replace(/^\s+/, '').replace(/\s+$/, ''); console.log("Текст " + value); 

And here is a working example on JSFiddle.

  • So it’s like I’ve got all the text jsfiddle.net/1xc89x34/1 - gilo1212
  • @ gilo1212, lying. In the console displays "Текст \nА этот нужно получить. \n" - Dmitriy Simushev
  • And now the extra whitespace around the edges removes - Dmitriy Simushev
  • Right, I'm lying! Thanks, everything works out. - gilo1212

Another option to check the type of node

 var $qtext = [].filter.call(document.querySelector('.qt').childNodes, node => node.nodeType == 3 && node.nodeValue.trim()).map(node => node.nodeValue.trim()); console.log($qtext.join('\n')); 
 <div> <div class='qt'> <span class="text1">этот не нужно получать<span class="text2">и этот тоже</span></span> А этот нужно получить. </div> </div>