0

This is a javascript function

<script>
function func1(var g){
alert(document.getElementsByTagName('p')[0].innerHTML);
}
</script>

how to pass value 0 from function call to function definition above.

<p onmouseover="func1(0)";>First para</p>
2
  • 6
    That's a JavaScript syntax error, to be more accurate. You can't have that var keyword in the formal parameter list. Keep your browser's developer console open so that you can see error messages. Commented Apr 21, 2016 at 13:06
  • OP, what is g meant to be doing in that function? At the moment it seems irrelevant. Commented Apr 21, 2016 at 13:12

2 Answers 2

2

Change it to

<script>
function func1(g){
  alert(document.getElementsByTagName('p')[0].innerHTML);
}
</script>

You need to see console log for relevant errors that pop up.

In this case you are declaring variable in function arguments which is not allowed, you can find out more about function here.

Sign up to request clarification or add additional context in comments.

4 Comments

The question remains - why pass in that parameter if it's not going to be used unless g is meant to replace the index.
Though it will work for sure.. You must have valid description which will make OP understand things! Change it/Try this will not help the cause...
No - he's clearly targeting the "First para" which is index 0.
We can create lots of use cases, OP should answer that.
1

Since you're using [0] to target the first paragraph when you mouseover it your function should be;

function func1(g){
  alert(document.getElementsByTagName('p')[g].innerHTML);
}

A more canonical JS approach is to attach an event listener to your elements with JavaScript instead of inlining the code:

var paras = document.getElementsByTagName('p');

[].slice.call(paras).forEach(function (el, i) {
  el.addEventListener('mouseover', func1.bind(func1, i), false);
});

function func1(g){
  console.log(paras[g].innerHTML);
}

DEMO

But perhaps the best way is to use event delegation so that you're not adding listeners to all the elements. Add an event listener to a parent element and catch the events from the paras as they bubble up the DOM:

var div = document.getElementById('paras');

div.addEventListener('mouseover', func1, false);

function func1(e) {
  var el = e.target;
  if (el.nodeType === 1 && el.nodeName === 'P') {
    console.log(el.innerHTML);
  }
}

DEMO

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.