0

I have this in my html page:

<div id="myDiv">
    <a href="www">
        LinkTitle
    </a>
</div>

I'm trying to get the content of tag 'a' ("LinkTitle"), inside a javascript variable.

This was my approach:

var myDiv = document.getElementById("myDiv");
var linkTitle = myDiv.getElementsByTagName("a").innerHTML;
alert(linkTitle);

And it returns null or undefined. Where did I go wrong and how could I fix this?

Jsfiddle: http://jsfiddle.net/NtV7T/

3
  • 2
    getElementsByTagName("a")[0] ? Commented May 19, 2014 at 15:05
  • getElementsByTagName("a") returns a list of a tags in the hmtml document. which need to be iterated Commented May 19, 2014 at 15:06
  • Oh, stupid mistake, how couldn't I figure this out :( thanks Commented May 19, 2014 at 15:10

3 Answers 3

2

Try

var linkTitle = myDiv.getElementsByTagName("a")[0].innerHTML;

As document.getElementsByTagName() returns an HTMLCollection of elements with the given tag name

Demo

Sign up to request clarification or add additional context in comments.

Comments

1

var linkTitle = myDiv.getElementsByTagName("a")[0].innerHTML;

getElementsByTagName returns array of elements

Comments

-1

The problem is that only the document element has the function getElementsByTagName. All the other HTML elements do not have it.

You could use the querySelector like this:

var myDiv = document.getElementById("myDiv");
var linkTitle = myDiv.querySelector("a")[0].innerHTML;
alert(linkTitle);

1 Comment

No, any element-nodes that can contain children are able to implement the getElementsByTagName() method; and querySelector() returns a single element-node (the first, and only the first) node that matches the selector.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.