Reputation: 1074
Does any one know where am I making my mistake ?
function functionTest(name) {
var Name = name;
alert(Name);
}
<h3 id="name" value="testingName"><a href="#"> test </a></h3>
<button onclick="functionTest(document.getElementById('name').value)"></button>
The output is undefined
Upvotes: 0
Views: 114
Reputation: 218847
<h3>
elements don't have a value
attribute. But you can use data-*
attributes instead. Something like this:
<h3 id="name" data-value="testingName">
Then you'd access it from the dataset
property:
document.getElementById('name').dataset.value
Example, using your original code
function functionTest(name) {
var Name = name;
alert(Name);
}
<h3 id="name" data-value="testingName"><a href="#"> test </a></h3>
<button onclick="functionTest(document.getElementById('name').dataset.value)"></button>
Upvotes: 4
Reputation: 1340
You have a bunch of semantic issues with your code. For starters, the value
attribute is usually only intended for <input>
tags.
If you really want to make the code work without modifying the HTML code, then document.getElementById('name').getAttribute('value')
will suffice, but that is adding one mistake after another.
What I would do is something like:
<h3 id="name" data-value="testingName"><a href="#"> test </a></h3>
<button onclick="functionTest(document.getElementById('name').getAttribute("data-value"))"></button>
This is semantically correct because headers (or any tag for that matter) can have attributes that start with data-
.
Upvotes: 2
Reputation: 15292
H3
dont have value attribute.It have innerHTML
attribute.
value
on it considered as custom user defined attribute.You can get it using getAttribute
If you want to get innerHTML
,then you should use like this
function functionTest(){
var Name = name ;
console.log(document.getElementById('name').innerHTML);
console.log(document.getElementById('name').getAttribute('value'))
}
Upvotes: 0
Reputation: 7091
You have to use getAttribute
on the element here is the corrected code
function functionTest(name) {
var Name = name;
alert(Name);
}
<h3 id="name" value="testingName"><a href="#"> test </a></h3>
<button onclick="functionTest(document.getElementById('name').getAttribute('value'))"></button>
Upvotes: 0
Reputation: 490
Use
<button onclick="functionTest(document.getElementById('name').getAttribute("value"))"></button>
Upvotes: -2