0
<html>
<head>
<script>
     function getTheValue()
     {

     }
</script>
</head>
<body>
    <div>
        <a href="http://google.com">
            <span class="text">Google</span>
        </a>
    </div>
    <div>
        <a href="http://yahoo.com"> 
            <span class="text">Yahoo</span>
        </a>
    </div>
    <input type="button" value="get" onclick="getTheValue()"></input>
</body>
</html>

Hi the above is my code in the I want the "href" value of yahoo using javascript but here I don't have any different classes but based on the child "span" value that is "Yahoo" I need to retrieve that "a" tag "href" value how?

srinu
  • 421
  • 3
  • 6
  • 12
  • 1
    Do you know how to retrieve this `Yahoo` tag? Your sounds like "I have A, I want B" problem. Show how you solve "A" problem, first. – Yeldar Kurmangaliyev Dec 15 '15 at 09:03
  • I am not able to understand how to solve the problem that's way I asked the doubt. I don't understand what your taking\ – srinu Dec 15 '15 at 12:13

2 Answers2

3

Use :contains

$( "span:contains('Yahoo')" ).closest("a").attr("href")

Javascript equivalent can be

function contains(selector, text) {
  var elements = document.querySelectorAll(selector);
  return [].filter.call(elements, function(element){
    return RegExp(text).test(element.textContent);
  });
}

contains("span", "Yahoo").parentNode.href; // Will be the element parent href.

Source for fucntion to fetch element based on content in Vanilla JS

Community
  • 1
  • 1
void
  • 36,090
  • 8
  • 62
  • 107
1

This code might solve the problem but the method getElementsByClassName() supports IE9 and Above or you can use getElementsByTagName(tagname)

 function getTheValue()
 {
     var patt = /Yahoo/i;
     var x = document.getElementsByClassName("text");
     var i;
     var spanElement;
     for (i = 0; i < x.length; i++) {
        if(patt.test(x[i].innerHTML))
        {
           spanElement = x[i];
           break;       
        }
     }
     var yourUrl = spanElement.parentNode.href;
     alert(yourUrl);
}
Faizaan
  • 11
  • 4