skip to Main Content

i tried to change this text using getElementsByTagName() but it did not work i do not know what is the probleme

enter image description here

getElementsByTagName()

2

Answers


  1. You should check the DOM documentation because you are misunderstanding what that function does, getElementsByTagName("s-button-text") isn’t getting the element because thats not how it works.

    This would work getElementsByClassName("s-button-text") or getElementsByTagName("span"), tag refers to the <span> in this case, and class refers to the class=" attribute.

    I would highly recommend you don’t use the second one as it will get other <span> elements in the page and not just the one you want.

    As well, even if you replace that it will create an error, this is how to do what you want to do:

    function change_content() {
       let elements = document.getElementsByClassName('s-button-text');
       for (let i=0; i<elements.length; i++) {
           elements[i].innerHTML = "newText";
       }
    }
    
    Login or Signup to reply.
  2. getElementsByTagName() returns an array of elements by tag name. You are trying to get an element by it’s class so you need a different method. You can use querySelector() or querySelectorAll().

    querySelector() is used to find a single element by a CSS selector.

    querySelectorAll() is used to get a list of elements by a CSS selector.

    This will find all elements with this class name and change the text of the first element returned:

    document.querySelectorAll('.s-button-text')[0].textContent = 'New text';
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search