1

How we can access a div from JavaScript?

<body>
  <div id="content">
    <p>this is para</p>
  </div>
  <button onclick="fun()">show it</button>
  <script>
    function fun() {
      var a = document.getElementById("content").value;
      alert(a);

    }
  </script>
</body>
Ivar
  • 6,138
  • 12
  • 49
  • 61
  • 4
    the div has no value you probably want the text of the p element? – Aalexander Feb 03 '21 at 09:44
  • @Ivar you are also doing same thing...so please don't give suggestion to any one if you are also doing same thing ok – Divyanshi Mishra Feb 03 '21 at 11:18
  • @DivyanshiMishra Did you see [what I edited](https://stackoverflow.com/posts/66024856/revisions)? I reformatted the code, removed some "fluff" and made the text a bit easier readable. I didn't add any solution to the post and everything is still as the original poster intended it. – Ivar Feb 03 '21 at 11:24

2 Answers2

0

The div has no value, textareas and input fields have values, you probably want the text content of the <p> element.
You can use querySelector here to access the <p> element inside your <div> with the id "content" and then read the text via the textContent property.

document.querySelector('#content > p').textContent;

<body>
  
        <div id="content">
          <p>this is para</p>
        </div>
        <button onclick="fun()">show it</button>
   
        <script>
            function fun(){
              var a= document.querySelector('#content > p').textContent;
                alert(a);

            }
        </script>
  
</body>
Aalexander
  • 4,987
  • 3
  • 11
  • 34
0

You may want to use ....innerHTML

function fun(){
  var a= document.getElementById("content").innerHTML;
    console.log(a);

}
<div id="content">
  <p>this is para</p>
</div>
<button onclick="fun()">show it</button>
caramba
  • 21,963
  • 19
  • 86
  • 127