Hello
Qwertyuiop
How ...">

Get an InnerHTML element that is not inside another tag

So, if I had

<div id="outside"> Hello <div id="inside"> Qwertyuiop </div> </div> 

How can I get InnerHTML from the outside without including anything from the inside or into any other HTML tags? (basically how to get "Hello")

+5
source share
7 answers

1 Interesting option:

This is not a serious answer and is based on Darin Morris' very destructive answer, but slightly less destructive:

 // Clone the element var $clone = $("#outside").clone(); // Remove all the children (leaves text nodes) $clone.children().remove(); alert($clone.text()); 

http://jsfiddle.net/TrueBlueAussie/ez4v83v5/4/

Again I would not recommend this as an alternative to say

2 My serious answer:

 $('#outside')[0].firstChild.nodeValue 

but who knows ... This technique may come in handy to someone at some point :)

+4
source

Another option:

 $(function(){ var theHtml = $("#outside"); var texto = theHtml[0].childNodes[0].data; alert((texto)); }); 

Working fiddle: http://jsfiddle.net/robertrozas/vhdbj1ck/1/

+3
source

Try using .contents() in this context

 alert($("#outside").contents().first()[0].nodeValue); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div id="outside"> Hello <div id="inside"> Qwertyuiop </div> </div> 
+2
source

You are trying to get the value of the first child, therefore

 alert($('#outside').prop('firstChild').nodeValue) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="outside"> Hello <div id="inside"> Qwertyuiop </div> </div> 
+2
source
 Array.prototype.filter.call(document.querySelector('#outside').childNodes, function (node) { return node.nodeValue; }); 

You can also try this in Vanilla, it would also handle the case if you had other lines after the div.

+1
source

There is probably a better way to do this, but this should work for you:

 var kids = $("#outside").children(); for(var i = 0; i < kids.length; i++) { if(kids[i].nodeType != 3) { $(kids[i]).remove(); } } alert($("#outside").text()); 

See this JSFiddle: http://jsfiddle.net/ez4v83v5/1

0
source

try jquery api children try fiddle

 $(document).ready(function(){ alert($('#outside').clone() //clone the element .children() //select all the children .remove() //remove all the children .end() //again go back to selected element .text()); }); 

hope this helps ...

0
source

Source: https://habr.com/ru/post/1204258/


All Articles