replace anchor text with jquery

Jquery

Jquery Problem Overview


i want to replace the text of a html anchor:

<a href="index.html" id="link1">Click to go home</a>

now i want to replace the text 'click to go home'

i've tried this:

alert($("link1").children(":first").val());
alert($("link1").children(":first").text());
alert($("link1").children(":first").html());

but it all gives me null or an empty string

Jquery Solutions


Solution 1 - Jquery

Try

$("#link1").text()

to access the text inside your element. The # indicates you're searching by id. You aren't looking for a child element, so you don't need children(). Instead you want to access the text inside the element your jQuery function returns.

Solution 2 - Jquery

To reference an element by id, you need to use the # qualifier.

Try:

alert($("#link1").text());

To replace it, you could use:

$("#link1").text('New text');

The .html() function would work in this case too.

Solution 3 - Jquery

$('#link1').text("Replacement text");

The .text() method drops the text you pass it into the element content. Unlike using .html(), .text() implicitly ignores any embedded HTML markup, so if you need to embed some inline <span>, <i>, or whatever other similar elements, use .html() instead.

Solution 4 - Jquery

Try this, in case of id

$("#YourId").text('Your text');

OR this, in case of class

$(".YourClassName").text('Your text');

Solution 5 - Jquery

function liReplace(replacement) {
	$(".dropit-submenu li").each(function() {
		var t = $(this);
		t.html(t.html().replace(replacement, "*" + replacement + "*"));
		t.children(":first").html(t.children(":first").html().replace(replacement, "*" +` `replacement + "*"));
		t.children(":first").html(t.children(":first").html().replace(replacement + " ", ""));
		alert(t.children(":first").text());
	});
}
  • First code find a title replace t.html(t.html()
  • Second code a text replace t.children(":first")

Sample <a title="alpc" href="#">alpc</a>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichelView Question on Stackoverflow
Solution 1 - JqueryLarry LustigView Answer on Stackoverflow
Solution 2 - JqueryzombatView Answer on Stackoverflow
Solution 3 - JqueryPointyView Answer on Stackoverflow
Solution 4 - JqueryMuhammad AttiqView Answer on Stackoverflow
Solution 5 - JqueryalpcView Answer on Stackoverflow