0
<div id="mess">
 <h1>Bhashyam School</h1>
 <p>AC Nagar Main Road, Nellore <br>Ho, Nellore - 524001  </p>
 <p class="tel">Telephone: +(91)-9603444376</p>
</div>

<form name="contactform" method="post" action="send.php" onsubmit="this.divcontent.value = document.getElementById('mess').innerHTML;">
    <p>
    <input id="box" type="text" name="telephone" placeholder="Enter Your Mobile Number. ex:988*******"><input type="hidden" name="divcontent" id="divcontent" value="" /> <button type="submit" class="button" value="Submit">Get Sms</button>
    </p>
</form>

Hello Friends we are developing sms form, i want to grab elements h1, p & p class=tel inside of <div id="mess"> when form has been submit (onsubmit event)

What is the correct javascript code to get element inside div tag elements?

slier
  • 6,511
  • 6
  • 36
  • 55
user2734770
  • 13
  • 1
  • 1
  • 4

2 Answers2

3

Here is a working demo of what you asked

jsfiddle

What I have done is added string to hidden field divcontent inside form

and updated onsubmit of form with

onsubmit="return getChilds();"

HTML

<div id="mess">
    <h1>Bhashyam School</h1>
    <p>AC Nagar Main Road, Nellore <br/>Ho, Nellore - 524001  </p>
    <p class="tel">Telephone: +(91)-9603444376 </p>
</div>

<form name="contactform" method="post" action="send.php" onsubmit="return getChilds();">
    <p>
        <input id="box" type="text" name="telephone" placeholder="Enter Your Mobile Number. ex:988*******"/>
        <input type="hidden" name="divcontent" id="divcontent" value="" /> 
        <button type="submit" class="button" value="Submit">Get Sms</button>
    </p>
</form>

JavaScript

<script type="text/javascript">
    function getChilds()
    {
        var arr=document.getElementById('mess').childNodes, str='';
        for(var i=0; i<arr.length; i++) {
            if(arr[i].innerHTML!=undefined) {
                str+=" "+(arr[i].textContent||arr[i].innerText);
            }
        }
        document.getElementById("divcontent").value=str;
        return true;
    }
</script>

better you should have some input with type hidden so hold such data and which is safe and better way of doing this task.

but why don't you go with jQuery for this, it offers better and cleaner way for doing many stuffs.

TheMohanAhuja
  • 1,855
  • 2
  • 19
  • 30
2
window.onload= function(){
  var elems = [];
  document.forms[0].onsubmit = function(){
    var nodes = document.getElementById('mess').childNodes;
    for (var i = 0 ; i < nodes.length; i++){
      if (nodes[i].nodeType == 1){
          elems.push(nodes[i].innerHTML);
      }
    }
    //console.log(elems);
  }
}

elems contains what u want

slier
  • 6,511
  • 6
  • 36
  • 55