Search code examples
javascript

How to select text by tag name in element?


I need to select title which is in div wrapped by h2, so i do something like this this.getElementsByTagName('h2') where this is current div in which is h2 - it returns current h2 element, but when i trying to get innerHTML or innerText it return null. What am I doing wrong?


Solution

  • it returns current h2 element, but when i trying to get innerHTML or innerText it return null. What am I doing wrong?

    getElementsByTagName returns a NodeList, not an element. The list doesn't have innerHTML, but each of its elements does, e.g.:

    var list = this.getElementsByTagName('h2');
    if (list[0]) {
        title = list[0].innerHTML;
    }
    

    Or if you're sure that it will exist:

    title = this.getElementsByTagName('h2')[0].innerHTML;
    

    ...but that will throw an exception if there are no h2's found.