1

i was just wondering if there is anyway i could copy text from a div with same class name into an input field

i am trying to copy text from the last div with same class name then paste into input field how could i do this?

<div class="message">TEXT HERE</div>

<div class="message">TEXT HERE</div>

<div class="message">COPY THIS TEXT TO INPUT</div>

<div id="input_box" class="td_input">
<input type="text" name="content" id="content">
</div>

sorry for my bad english

  • 1
    `i am trying` Yes, there might be a way, have you tried anything at all yourself yet? Please post the code – CertainPerformance Aug 15 '18 at 03:40
  • 1
    Break it apart into steps and you should be able to research yourself towards an answer quite easily! **(1)** [Get the last element of a certain class](https://stackoverflow.com/questions/39223343/shortest-way-to-get-last-element-by-class-name-in-javascript) **(2)** [Get the text from that element](https://stackoverflow.com/questions/10370204/how-can-get-the-text-of-a-div-tag-using-only-javascript-no-jquery) **(3)** [Populate the input](https://stackoverflow.com/questions/5700471/set-value-of-input-using-javascript-function) – Tyler Roper Aug 15 '18 at 03:43

3 Answers3

1

After select all div message Use nodes[nodes.length- 1] for last div

var nodes = document.querySelectorAll('.message');
var last = nodes[nodes.length- 1];
document.querySelector('#content').value =last.innerHTML;
<div class="message">TEXT HERE</div>

<div class="message">TEXT HERE</div>

<div class="message">COPY THIS TEXT TO INPUT</div>

<div id="input_box" class="td_input">
<input type="text" name="content" id="content">
</div>
Mohammad Ali Rony
  • 4,695
  • 3
  • 19
  • 33
0

Try this one using jquery:

  $(document).ready(function(){
  var value = $(".message").last().text();
document.getElementById('content').value = value
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
    <div class="message">TEXT HERE</div>

    <div class="message">TEXT HERE</div>

    <div class="message">COPY THIS TEXT TO INPUT</div>

    <div id="input_box" class="td_input">
    <input type="text" name="content" id="content">
    </div>
    </body>
    </html>
Jun
  • 138
  • 1
  • 9
0

use below code

var elems = document.getElementsByClassName("message");
var lastElem = elems[elems.length - 1];
document.getElementById("content").value = lastElem.innerText;
Shiv Kumar Baghel
  • 2,464
  • 6
  • 18
  • 34