2016-03-26 5 views
4

Zuerst erstelle ich eine Bibliothek für JavaScript und kann jQuery nicht verwenden. Ich versuche, den Textinhalt eines HTML-Elements ohne den Textinhalt seiner untergeordneten Elemente abzurufen.JavaScript get textContent mit Ausnahme von Kindern

Beide Attribute innerText und textContent geben mir nicht, was benötigt wird, bitte helfen.

Antwort

2

Sie können die DOM-API als childNodes und nodeType lösen.

var elChildNode = document.querySelector("#hello").childNodes; 
var sChildTextSum = ""; 

elChildNode.forEach(function(value){ 
    if(value.nodeType === Node.TEXT_NODE) { 
     console.log("Current textNode value is : ", value.nodeValue.trim()); 
     sChildTextSum += value.nodeValue; 
    } 
}); 

console.log("All text value of firstChild : ", sChildTextSum); 

Ich habe einen Beispielcode wie oben erstellt.

https://jsfiddle.net/nigayo/p7t9bdc3/

1

Um Author's Name aus dem folgende Elemente zu erhalten, ohne <span>...:

<div class="details__instructor"> 
    Author's Name<span ng-show="job_title">, Entrepreneur</span> 
</div> 

Verwendung childNodes[0]. Zum Beispiel:

document.querySelector('div.details__instructor').childNodes[0] 

Das Ergebnis ist ein Objekt:

"Author's Name"