user3437526
user3437526

Reputation: 3

Check if a div has an ID that contains a string plus a variable

I feel there will be a very amateur mistake I'm making with this, but after an entire day of pulling what hair I have left out, here goes:

I need to be able to check if a div exists on the page that contains as it's ID a string + a variable which is being generated when the mouse hovers over another div.

For example:

I have a DIV on my sidebar navigation that contains the words 'Google' in a span.

When the user hovers over this div, I create a variable that contains the text from the span, let's call this variable sideBarButtonName.

I then would like to search the DOM for any divs whose ID contains the word "nav_" + sideBarButtonName and if such a div exists, throw an alert.wb If this doesn't exist, there is an else statement I have that is working just fine.

I cannot get this right! Help!

The part I'm struggling with is the count that checks if the

 $("div[id*='nav_']") + (sideBarButtonName).length > 0

I've created a fiddle that replicates the issue I'm having.

http://jsfiddle.net/Pu5FJ/1/

Thanks!

Upvotes: 0

Views: 75

Answers (3)

Ja͢ck
Ja͢ck

Reputation: 173562

From your fiddle it seems that "contains" really means equals, so:

if ($('#nav_' + sideBarButtonName).length) {
    // alert here
}

Demo

However, seeing your HTML structure, you may wish to improve it a little:

<div class="sideBarButton" data-url="http://www.google.com">
    <div id="nav_Google" class="side-nav">
    </div>
    <span>Google</span>
</div>

Then you check whether an element with "side-nav" class exists inside:

$('.sideBarButton').mouseenter(function() {
    if ($(this).find('.side-nav').length) {
        // alert here
    }
});

Upvotes: 1

Sridhar R
Sridhar R

Reputation: 20418

 $("div[id='nav_" + sideBarButtonName + "']").length > 0) {

or

$("div #nav_" + sideBarButtonName + "").length > 0)

DEMO

Upvotes: 0

billyonecan
billyonecan

Reputation: 20260

You need to put sideBarButtonName inside of the selector. As your ID is an exact match, you can target it directly:

$('#nav_' + sideBarButtonName).length

Here's a fiddle

Upvotes: 1

Related Questions