Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Get child's text value

How can I get the text value from an elements's child?

Say I have this code on a page:

<div class='geshitop'>
  &#91; CODE &#93; &#91; <a href="#" onclick="javascript:copy(); return false;">PLAIN-TEXT</a> &#93;
</div>
<div class='geshimain'>
  <pre><div class="text" style="font-family:monospace;">Code goes here...</div></pre>
</div>

The function copy():

<script type="text/javascript">
function copy() {
    var text = this.parent.getElementsByName("text");
    var code = text[0].value;
    var popup = window.open("", "window", "resizeable,width=400,height=300");
    popup.document.write("<textarea name='code' cols='40' rows='15'></textarea>");
    popup.code.value = code;
}

How would I go about getting that child's data: the <div class "text">. How can I get that from the parent?


I'm still having problems. If there is two codeboxes on one page, then it does not work. Remember, I am unable to use ID's. It must be classes.

If I was able to use jQuery this would be easy.

like image 936
James Brooks Avatar asked May 23 '26 18:05

James Brooks


2 Answers

Get a reference to the node you want to retrieve text from and try:

someNode.firstChild.nodeValue

When you have a node like this:

<span>Here is some text</span>

You're actually looking at two nodes, a span node which has a text node child. In DOM, that text node child's nodeValue is "Here is some text"

like image 100
Maciek Avatar answered May 26 '26 07:05

Maciek


put an ID on the tag you want to get its data from.

this way will only grab the first child of the div node:

function copy(){
     var text = document.getElementById( "YOU_TAG_NAME" ).firstChild;
     //do stuff
}

this will grab all of the data in the node, but don't do this unless you have control over what goes into that div tag:

function copy(){
     var text = document.getElementById( "YOU_TAG_NAME" ).innerHtml;
     //do stuff
}
like image 29
linusthe3rd Avatar answered May 26 '26 07:05

linusthe3rd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!