Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get InnerHTML of element that isnt inside another tag

So if I had

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

How would I get the InnerHTML of the outside without including anything from the inside or any other HTML tags? (bascially how to get "Hello")

like image 969
Sarah Pierson Avatar asked Oct 08 '14 13:10

Sarah Pierson


People also ask

Can you += innerHTML?

Appending to innerHTML is not supported: Usually, += is used for appending in JavaScript. But on appending to an Html tag using innerHTML, the whole tag is re-parsed.

How use innerHTML with div tag?

Using the innerHTML attribute: To append using the innerHTML attribute, first select the element (div) where you want to append the code. Then, add the code enclosed as strings using the += operator on innerHTML.

Why you should not use innerHTML in JavaScript?

The use of innerHTML creates a potential security risk for your website. Malicious users can use cross-site scripting (XSS) to add malicious client-side scripts that steal private user information stored in session cookies.


1 Answers

1 An interesting option:

This is not a serious answer, and is based on Darin Morris' highly destructive answer but is 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 for someone at some point :)

like image 143
Gone Coding Avatar answered Sep 21 '22 14:09

Gone Coding