[英]How to use javascript to replace this html?
I want to use javascript here, not jquery. 我想在这里使用javascript,而不是jquery。 How do I replace this html text?
如何替换此html文本?
How do I replace the 1 with a 5? 如何用1代替1? I tried this but it didn't work.
我试过了,但是没有用。
document.getElementsByClassName('hello').innerHtml=5
<li class='hello'> <a tabindex="0" aria-label="Page 1 is your current page" aria-current="page">1</a> </li>
document.querySelector( '.hello a' ).innerHTML = 5;
document.getElementsByClassName()
will give you a live HTMLCollection
containing your <li>
element. document.getElementsByClassName()
将为您提供一个包含您的<li>
元素的实时HTMLCollection
。 You need to use document.querySelector()
to select the <a>
. 您需要使用
document.querySelector()
选择<a>
。
The above solution will only work, if there is only one <a>
matching that selector. 仅当只有一个
<a>
与该选择器匹配时,以上解决方案才有效。 Otherwise you would have to use document.querySelectorAll()
and change for all elements or pick the right one. 否则,您将不得不使用
document.querySelectorAll()
并更改所有元素或选择正确的元素。
Use, 采用,
document.querySelector(".hello a").innerHTML = 5;
The problem is that you are selecting the <li>
element and not the <a>
inside it. 问题在于您正在选择
<li>
元素,而不是其中的<a>
。
Since you don't want to use jQuery, here is a JS function to consider: 由于您不想使用jQuery,因此需要考虑以下JS函数:
function updateAnchorText(className, anchorText)
{
// NOTE: you could make 'anchorText' an integer value that is incremented during each update and set using .ToString()
var liElems = null;
var aElems = null;
var liElem = null;
var aElem = null;
var i,j;
try
{
liElems=document.getElementsByClassName(className);
if(liElems!=null)
{
for(i=0;i<liElems.length;i++)
{
liElem = liElems[i];
aElems=liElem.getElementsByTagName("a");
if(aElems!=null)
{
for(j=0;j<aElems.length;j++)
{
aElem = aElems[j];
aElem.innerHTML=anchorText;
}
}
}
}
}
catch(e)
{
alert("Error: " + e.Message);
}
finally
{
}
return;
}
Call it using updateAnchorText("hello", "5"); 使用updateAnchorText(“ hello”,“ 5”);进行调用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.