1

This is what I want to know if we can access multiple html file elements from the same external javascript file.

Scenario:

one.html

<div id="one" onclick="oneDIV"></div>

two.html

<div id="two" onclick="twoDIV"></div>

script.js

function oneDIV(){
    var instance = document.getElementById("one");
}


function TwoDIV(){
    var instance = document.getElementById("two");
}

The question would be more specific if I ask One JS File for Multiple Pages

2
  • Can you expand on your question? How are the html files loaded and how is the script used Commented Feb 6, 2014 at 8:51
  • It is a bit hard to understand your question. Commented Feb 6, 2014 at 8:54

2 Answers 2

1

If I understood your question correctly, you want to have a single function which does something with the clicked DIV.

You can achieve this with the this keyword. this references the DOM object from which the event was triggered in this case.

For example if you want to alert the DIV's content you can do it like this:

<div id='one' onClick='shout()'>foo</div>
<div id='two' onClick='shout()'>bar</div>

<script type='text/javascript'>
    function shout(){
        alert(this.innerHtml());
    }
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

If I didn't understand it correctly, please comment. I will edit it.
Hi, thanks for your reply. What I actually meant was the way I've defined those two functions inside the external script file, is it the right way to do it, because I cannot access the div of one.html file but the div of two.html is working fine and getting accessed.
0

not sure but try <script src="script.js" type="text/javascript"></script>
in the <head> tag in one.html and two.html
tell if it worked or not.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.