Joseph Sala
Joseph Sala

Reputation: 23

javascript - get attribute value by text value

<a href='http://example.com'>Goes To Example.com</a>

I want to get the href value of this. This link will always be on the page

I will usually do something like: document.getElementsByTagName('a')[5]. However, the number of links are always changing so it isn't reliable at all. Is there a way I can get it by the text Goes To Example.com?

Upvotes: 2

Views: 1200

Answers (5)

user663031
user663031

Reputation:

You could use xpath:

document.evaluate(
    '/html/body//a[text()='Goes To Example.com']/@href', 
    document, null, XPathResult.ANY_TYPE, null);

You can iterate over the result (which is of type XPathResult) using iterateNext.

See xpath documentation for details: https://developer.mozilla.org/en-US/docs/Web/API/document.evaluate.

Upvotes: 1

therealrootuser
therealrootuser

Reputation: 10904

Use the JQuery :contains() selector. You can then get the attribute "href", as follows:

$("a:contains(Goes To Example.com)").attr("href");

For example, the following snippet will popup an alert with http://example.com inside it:

<html>
    <head>
        <script src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
    </head>
    <body>
        <a href='http://example.com'>Goes To Example.com</a>

        <script>
            alert($("a:contains(Goes To Example.com)").attr("href"));
        </script>
    </body>
</html>

Upvotes: 1

Viswanath Donthi
Viswanath Donthi

Reputation: 1821

You can do it like this:

var links = document.getElementsByTagName('a');
var requiredId = "";
for(var i=0; i<links.length; i++){
    if(links[i].innerHTML == "Goes To Example.com"){
        requiredId = links[i].getAttribute('id');
    }
}

Upvotes: 0

Mritunjay
Mritunjay

Reputation: 25882

As you said in comment you can use jquery, use Contains like bellow

$('a:contains("Goes To Example.com")')

DEMO

Upvotes: 2

V31
V31

Reputation: 7666

You can do document.getElementById and give the id to the a tag. To get the text you can use innerHTML function

Working Fiddle

HTML Markup

<a id="test" href='http://example.com'>Goes To Example.com</a>

JS:

document.getElementById("test").innerHTML

If you want it by href attribute only then you have to loop it over

var els = document.getElementsByTagName("a");
for (var i = 0, l = els.length; i < l; i++) {
    var el = els[i];
    if (el.href === 'http://www.example.com/') {
        alert(el.innerHTML);
    }
}

Upvotes: 0

Related Questions