-1

I want to use javascript here, not jquery. How do I replace this html text?

How do I replace the 1 with a 5? 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>
mason
  • 31,774
  • 10
  • 77
  • 121
Jwan622
  • 11,015
  • 21
  • 88
  • 181
  • Describe "didn't work". Did you get an error message? – mason Jun 30 '17 at 20:13
  • Nope, it just added a new property called innerHtml to the `li` but did nothing to the nested `a` tag. Does that sound right? – Jwan622 Jun 30 '17 at 20:14
  • 2
    Yes. Always make sure that in the future if you have something that doesn't work, you need to explain what you mean by doesn't work. Say what it's doing, include relevant error messages etc. Fortunately this question was a simple one, but that's not always the case. – mason Jun 30 '17 at 20:17
  • https://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method – epascarello Jun 30 '17 at 20:26

3 Answers3

2
document.querySelector( '.hello a' ).innerHTML = 5;

document.getElementsByClassName() will give you a live HTMLCollection containing your <li> element. You need to use document.querySelector() to select the <a>.

The above solution will only work, if there is only one <a> matching that selector. Otherwise you would have to use document.querySelectorAll() and change for all elements or pick the right one.

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
Sirko
  • 72,589
  • 19
  • 149
  • 183
0

Use,

document.querySelector(".hello a").innerHTML = 5;

The problem is that you are selecting the <li> element and not the <a> inside it.

Sid24
  • 334
  • 3
  • 14
0

Since you don't want to use jQuery, here is a JS function to consider:

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");