简体   繁体   中英

get text of anchor tag and display it in html tag

I'm using the below code and its working fine for me, for one anchor tag.

<h1 id="h1">heading</h1>
<a type="button" id="demo" onclick="Func()">sign-up</a>

JS

function Func() {
    document.getElementById("h1").innerHTML = "sign-up";
}

How to do this for 3 or 4 anchor tags ?

What I actually want is everytime when clicked on anchor tags get its text and display it in the only one <h1></h1> tag

Any answer will be appreciated either JS or JQuery

You can add class to all the links and based on that add a click event handler for them.

 $(".buttons").click(e => $("#h1").text(e.currentTarget.textContent)); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h1 id="h1">heading</h1> <a type="button" class="buttons">sign-up</a> <a type="button" class="buttons">sign-in</a> 

you should try JQuery like

your h1 tag like

<h1 id="anchorText"> </h1>

and your anchor tags like

<a type="button" id="demo">sign-up</a>
<a type="button" id="demo1" >Login</a>

Now in your jquery

$("a").click(function(){
    $("#anchorText").text($(this).text());
});

You can pass this in the Func() to refer to the clicked element and then get the innerHTML (or innerText) of that element based on your convenience.

 function Func(e) { document.getElementById("h1").innerHTML = e.innerHTML; } 
 <h1 id="h1">heading</h1> <a type="button" id="demo1" onclick="Func(this)">sign-up</a> <a type="button" id="demo2" onclick="Func(this)">sign-in</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