Reputation: 670
I am trying to get src value from html button when user clicks it.
<button type="button" value="95" id="load" onclick="functionName(this.src,this.value);">
<img src="https://www.drupal.org/files/druplicon-small.png">
<span>Welcome</span>
</button>
Successfully getting value from this.value
but this.src
is not giving any value.
Upvotes: 0
Views: 425
Reputation: 11
It is normal, when u pass the this to the function, the this is your button, or in your case the this.value is the attribute value of your button and the this.src the value of your button attribute src, and you dont have the button src attribute
What can you do?:
Is something like this:
function functionName(button) {
var buttonValue = button.value;
var imageSrc = button.getElementsByTagName('img')[0].getAttribute('src');
}
<button type="button" value="95" id="load" onclick="functionName(this);">
<img src="https://www.drupal.org/files/druplicon-small.png">
<span>Welcome</span>
</button>
Upvotes: 1
Reputation: 50326
Pass the context this
& use children
method.The button does not have src
property,it belongs to the img
tag, so children
will give array of children.
function functionName(elem) {
//elem will be button itself
var _childImg = elem.children[0].src
console.log(_childImg, elem.value)
}
<button type="button" value="95" id="load" onclick="functionName(this);">
<img src="https://www.drupal.org/files/druplicon-small.png">
<span>Welcome</span>
</button>
Upvotes: 0
Reputation: 1657
How about using the querySelector
to target the image source
Example:
function functionName(button) {
var src = button.querySelector("img").src;
console.log(src);
}
<button type="button" value="95" id="load" onclick="functionName(this);">
<img src="https://www.drupal.org/files/druplicon-small.png">
<span>Welcome</span>
</button>
Upvotes: 0
Reputation: 22564
this
is referring to the button which doesn't have the src
attribute. Image inside the button has the src
attribute.
You can pass this
to your function and access src
of the image using button.children[0].src
or button.getElementsByTagName('img')[0].src
function functionName(button, value) {
let src1 = button.children[0].src;
let src2 = button.getElementsByTagName('img')[0].src;
console.log(src1, src2, value);
}
<button type="button" value="95" id="load" onclick="functionName(this,this.value);">
<img src="https://www.drupal.org/files/druplicon-small.png">
<span>Welcome</span>
</button>
Upvotes: 0