Trouble with finding class element names in Javascript

64 views Asked by At

I'm trying to grab the Names of some Class Elements in a document (there are several of them) and rotate through them.

The HTML code of the site looks like this:

<div class="parent">
   <div class="item">
      <a class="item-name" href="http://somerandomurl.com">Relevant Item</a>

If I wanted to grab the URL I know the solution already:

function searchItem(itemname) {
    listings = $(".item-name");
    for(var i = 0; i < links.length; i++) {
        element = listing[i];
        if(element.href.indexOf(itemname) !== -1) {
            return true; 
          } 
    }
}

In this case however, I don't want to compare the URL against another URL, I need to grab the Title off the "item-name" class as String and compare it to other Strings.

How can I manage to do this? I have tried a few things already, like listings = $(".market-name market-link").text();.

2

There are 2 answers

0
jezrael On BEST ANSWER
function searchItem(itemname) {

    if($('a.item-name:contains("' + itemname + '")').length) {
        //console.log("true"); 
        return true;
    }
}

jsfiddle

1
pSaadi On

First, yo are looping through the wrong variable.

You should loop through listing instead of links

Then compare it to the element HTML:

function searchItem(itemname) {
    listings = $(".item-name");
    for(var i = 0; i < listing.length; i++) {
        element = listing[i];
        if(element.html().indexOf(itemname) !== -1) {
            return true; 
          } 
    }
}