简体   繁体   中英

How can get the text of <a> tag without id using only javascript

I am attaching a javascript to the following a tag section

<a class="btn-button button" onclick="myAlert()">
</a>

And this is my javascript function

<script>
    function myAlert() {
        alert('Test..');
    }
</script>

How can I get the current text been assigned when the javascript will fire? As you can see there is not id been set in the a tag.

EDIT I know that right now there is not value but I was just copy my actually code. At some point there will be a values since it is used from other components including Angular.

I can't tell which proper Angular way to do this as you haven't shared Angular code, but this is how it can be done in vanilla HTML/JS:

In the onclick , set this as an argument to your function, so that you can receive the HTML element that called it.

Then you can use either textContent or innerText (see list of their differences in this MDN page ) to get or change the text value.

 function myAlert(element) { alert('Test..' + element.textContent); //adding something so that we can see it's dynamic element.textContent += ' bla'; }
 <a class="btn-button button" onclick="myAlert(this)"> click me</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