skip to Main Content

I have some HTML like this

<div id='div1'>some content</div>
<div id='div2'>some other content/div>
<div id='div3'>now some even different content</div>

<button onclick='CallThis(1);'>Alert 1</button>
<button onclick='CallThis(2);'>Alert 2</button>
<button onclick='CallThis(3);'>Alert 3</button>

<script>
    function CallThis(SomeVar)
    {
       alert(document.getElementById('div' + SomeVar).innerHTML);
    }
</script>

I want to use simple javascript. How can I accomplish this?

Thanks for your help.

3

Answers


  1. Not really sure of what are you trying to accomplish, but if you would like to show some alert that varies with the clicked button, you can use if statement like below:

    <script>
    function CallThis(SomeVar){
        text = '';
        if (SomeVar == '1'){
            text = 'some content';
        } else if(SomeVar == '2'){
            text = 'some other content';
        } else {
            text = 'now some even different content';
        }
        alert(text);
    }
    </script>
    

    it really is just a basic JavaScript, maybe try to learn the fundamental first, here’s a page to learn the fundamental of JavaScript :
    JavaScript Tutorial

    Login or Signup to reply.
  2. The only thing i noticed was a typo in the second line, if we fix that, then it works.

    function CallThis(SomeVar) {
       alert(document.getElementById('div' + SomeVar).innerHTML);
    }
    <div id='div1'>some content</div>
    <div id='div2'>some other content</div>
    <div id='div3'>now some even different content</div>
    
    <button onclick='CallThis(1);'>Alert 1</button>
    <button onclick='CallThis(2);'>Alert 2</button>
    <button onclick='CallThis(3);'>Alert 3</button>
    Login or Signup to reply.
  3. You need to learn DOM Traversing,
    or name efficiently
    try use querySelectorAll("div")

    function CallThis(SomeVar){
            alert(document.querySelectorAll('div')[SomeVar-1].innerHTML);
        }
    

    more intuitive way of coding can help debug

    <button onclick='CallThis("div1");'>Alert 1</button>
    <button onclick='CallThis("div2");'>Alert 2</button>
    <button onclick='CallThis("div3");'>Alert 3</button>
    function CallThis(div){
            alert(document.getElementById(div).innerHTML);
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search