Javascript - get child text value

How to get text value from child elements?

Let's say I have this code on the 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>

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 can I get the data from this child element: <div class "text">. How can I get this from a parent?


I'm still having problems. If there are two code blocks on one page, this will not work. Remember, I cannot use identifiers. These should be classes.

If I could use jQuery, that would be easy.

+3
source share
4 answers

Try the following:

HTML . "javascript:" onclick. , "this" :

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

, , . node. , , < div class= " > < div class=" geshimain" > node, , . :

function copy(node) {
    node = node.parentNode; // <div class="geshitop">

    // Loop over adjacent siblings, looking for the next geshimain.
    while (node.nextSibling) {
        node = node.nextSibling;
        if (node.nodeName === 'DIV' && node.className === 'geshimain') {
            break;
        }
    }

    if (!node) {
        throw new Error("Could not locate geshimain");
    }

    // Locate the <div class="text">
    node = (function () {
        var divs = node.getElementsByTagName('div');
        for (var x = 0; x < divs.length; x++) {
            if (divs[x].className === 'text') {
                return divs[x];
            }
        }
        return null;
    }());

    if (!node) {
        throw new Error("Could not locate text");
    }

    node =
    '<textarea name="code" cols="40" rows="15">' + node.innerHTML + "</textarea>";
    popup = window.open("", "window", "resizeable,width=400,height=300");
    popup.document.write(node);
    popup.document.close();
}

!

0

node, , :

someNode.firstChild.nodeValue

node, :

<span>Here is some text</span>

, node, node child. DOM node child nodeValue - " "

+8

: css "text" ?

, id, , .

0

, .

div node:

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

node, , , div:

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

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


All Articles