J4GD33P 51NGH
J4GD33P 51NGH

Reputation: 670

How to get value of child tag of a button tag

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

Answers (4)

simao pedro lemos
simao pedro lemos

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?:

  • Pass the only the param this to your function and over there, get the value of your attribute value.
  • Inside your function, through the this, get the children image and get it attribute src

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

brk
brk

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

Vincent1989
Vincent1989

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

Hassan Imam
Hassan Imam

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

Related Questions