简体   繁体   中英

Can I get the parent Div tag innerHTML from a child span click event see code

<body>
  <div class='Myclass'>
     Value I Want, I have already got the span inner html, but I want to add the the value of the div
     <span onclick='Some javascript to get div value'>some html</span>
  </div>
</body>

Tell me if I can improve this answer.

Please thank @JoshCrozier for his jsfiddle ( https://jsfiddle.net/1p2j4em7/ ) which imparted some new information for this answer to be the best it could be.

 function getText(elem){ alert(elem.previousSibling.nodeValue.trim()) } 
 <body> <div class='Myclass'> Value I Want, I have already got the span inner html, but I want to add the the value of the div <span onclick='getText(this);'>some html</span> </div> </body> 

Here is a solution that is generic for as many divs as you want.

 window.addEventListener('load', function() { var divs = document.getElementsByClassName('Myclass'); for (var i = 0; i < divs.length; i++) { divs[i].children[0].onclick = function() { alert(this.previousSibling.nodeValue.trim()) } } }); 
 <body> <div class='Myclass'> Value I Want, I have already got the span inner html, but I want to add the the value of the div <span onclick='getText(this);'>some html</span> </div> </body> 

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