Question

I am trying to return and capture in a variable the next immediate anchor tag of the string that is matched. I want to only get the single anchor tag following the matched string and nothing else. This is where I am stuck. Here is the code and jsfiddle.

<body>

<p id="demo">Click the button to display the matches.</p>
<p><strong>Regular Edition of 325</strong></p>
<a href="link1.html">Link 1</a>
<p><strong>Regular Edition of 658</strong></p>
<a href="link2.html">Link 2</a>
<p><strong>Regular Edition of Something Else</strong></p>
<a href="link3.html">Link 3</a>
<p></p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction(){
parseIt = $("p").find("strong").text();
matchIt();
}
function matchIt(){
resIt = parseIt.match(/Regular Edition of 325/);
document.getElementById("demo").innerHTML=resIt;
console.log($(resIt));
}

</script>

</body>

http://jsfiddle.net/pbpyrojust/V86t6/6/

Any help is greatly appreciated. Also let me know if you need more information.

Was it helpful?

Solution

If you want an attribute from the anchors, then it's easier to loop through the "a" tags instead of the paragraph nodes. You can use jQuery's "prev()" method to access the preceding "p" and check that its text matches your regex. http://jsfiddle.net/V86t6/13/

function myFunction(){
  var mtch = new RegExp(/Regular Edition of 325/);
  $('a').each(function () {
    if($(this).prev().find("strong").text().match(mtch)) {
      document.getElementById("demo").innerHTML=$(this).attr("href")
    }
  });
}

Note that this code will break if the html changes. Consider wrapping each label/link in a div and iterating over the containers rather than traversing using prev/next/closest, etc.

Since a pure JS version was called for (http://jsfiddle.net/V86t6/15/):

function myFunction(){
  var mtch = /Regular Edition of 325/;
  Array.prototype.forEach.call(
    document.querySelectorAll('p strong'),
    function(strong) {
      if(strong.innerHTML.match(mtch))
        document.getElementById("demo").innerHTML = strong.parentNode.nextElementSibling.href;
    }
  );
}

OTHER TIPS

You can use .filter to get the p element via the matched text:

function myFunction(){
    parseIt = $("p").find("strong");
    matchIt();
}
function matchIt(){
    resIt = parseIt.filter(function () {
        return $(this).text().match(/Regular Edition of 325/);
    });
    document.getElementById("demo").innerHTML= resIt.parent().next().text();
}

http://jsfiddle.net/V86t6/7/


Side note: don't communicate between functions via global variables. Each function should just be using its own local variables or closed-over variables.

You can simplify this a lot by doing something like this:

function myFunction() {
    parseIt = $("p strong").filter(function () {
        return this.innerText.match(/Regular Edition of 325/);
    });
    var anchor = parseIt.parent().next("a");
}

http://jsfiddle.net/V86t6/9/

I used this:

$('button').click(function() {
    $('p.search').each(function() {
        if(this.innerHTML.match(/Regular Edition of 325/)) {
            var $link = $(this).next('a');
            $('#demo').text($link.text());
            console.log($link);
        }
    });
});

On button click, it loops through every element you want to search. If the elements contents match the regex, then we find the next link. After this, you can do anything with the link.

JSFiddle


UPDATE:

Here is a pure-JS version. Note, that this is only compatible with IE 9+ because of my use of document.getElementsByClassName().

document.getElementById('trigger').addEventListener('click', function() {
    var paragraphs = document.getElementsByClassName('search');
    for(var i = 0; i < paragraphs.length; i++) {
        var paragraph = paragraphs[i];
        if(paragraph.innerHTML.match(/Regular Edition of 325/)) {
            var link = paragraph.nextSibling;
            while(link) {
                if(link.tagName === 'A') {
                    document.getElementById('demo').innerHTML = link.innerHTML;
                    console.log(link);

                    break;
                }

                link = link.nextSibling;
            }
        }
    }
});

JSFiddle

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top