简体   繁体   中英

Get a child element tag in html using Javascript in the onclick attribute

Using pure javascript, I want to reference the first inner html element within an <a> element, by using the parent's onclick attribute. I tried to use both firstChild and firstChild.InnerHTML , but I could not get my element.

For example, the following html code:

<a href="#" onclick="showImg(this.firstChild.innerHTML)">
  <img src="imgs/placeholder.png" alt="My Image" title="image-name" >
  <p>This is a paragraph</p>
  <div>This is a div</div>
</a>

I want to get the <img> element as a parameter into the function showImg() , so I can obtain the title attribute to feed into an image path to be displayed in a modal window/popup.

The same modal window would be displayed using the same function, BTW.

Is this possible to achieve? (Please note that I want to grab the entire element, not just an attribute.)

Doing this because there is no permission to add jquery or other similar libraries.

UPDATE: I am looking for code that works on IE from version 7 upward.

MY SOLUTION: I finally ended using the getAttribute method, after combining both first firstElementChild and children[0] as per details from this answer .

My final solution looks like this:

<a href="javascript:void(0)" 
   onclick="showImg((this.firstElementChild || 
                     this.children[0]).getAttribute('title'))">
  <img src="imgs/placeholder.png" alt="My Image" title="image-name" >
  <p>This is a paragraph</p>
  <div>This is a div</div>
</a>

And this is the script:

  function getImg(img) {        
    var container = document.getElementById("some-id");
    var imgPath = 'imgs/' +img+ '.png';
    container.src = imgPath;
  }

Thanks for the insight.

This should do the trick:

 function showImg(image) { console.log(image); } 
 <a href="#" onclick="showImg(this.children[0].getAttribute('title'))"> <img src="imgs/placeholder.png" alt="My Image" title="image-name" > <p>This is a paragraph</p> <div>This is a div</div> </a> 

If you want the whole element, replace the onclick with: onclick="showImg(this.children[0])"

您应该使用getAttribute函数

<a href="#" onclick="showImg(this.firstElementChild.getAttribute('title')">

Use this.firstElementChild.outerHTML

<a href="#" onclick="alert(this.firstElementChild.outerHTML)">
  <img src="imgs/placeholder.png" alt="My Image" title="image-name" >
  <p>This is a paragraph</p>
  <div>This is a div</div>
</a>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM