Jamie Southwell
Jamie Southwell

Reputation: 93

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

Upvotes: 1

Views: 1403

Answers (3)

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

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>

Upvotes: 1

Rahul Dudharejiya
Rahul Dudharejiya

Reputation: 375

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());
});

Upvotes: 2

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28445

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>

Upvotes: 2

Related Questions