Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery with the plus sign

I wonder why jQuery doesn't allow "+" sign. Here is an example of how it works with "1" and "3" but not with "2+". Just mouse-over the text above every div.

<div id="div-2+"></div>

JSFiddle

$('a.hover').mouseover(function() {

    dataI = $(this).data('i');

	$('div#div-' + dataI).addClass('h');

});

$('a.hover').mouseout(function() {

    dataI = $(this).data('i');

	$('div#div-' + dataI).removeClass('h');

});
a {
    display: inline-block;
    width: 100px;
    margin: 60px 20px 60px 0;
    text-align: center;
}

div {
    display: inline-block;
    width: 100px;
    height: 100px;
    margin-right: 20px;
    background-color: #ddd;
}

div.h {
    background-color: #f00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a class="hover" data-i="1">DIV 1</a>

<a class="hover" data-i="2+">DIV 2+</a>

<a class="hover" data-i="3">DIV 3</a>

<br />

<div id="div-1"></div>

<div id="div-2+"></div>

<div id="div-3"></div>
like image 585
medk Avatar asked May 11 '15 22:05

medk


1 Answers

Most-likely because the plus sign is the adjacent CSS selector, which causes the Sizzle selector library jQuery uses to assume you mean an adjacent selector.

One way around this would be to use an attribute selector, that selects the id attribute. Although many people would argue putting a plus sign in the id is a bad idea.

Working Example:

$('a.hover').mouseover(function() {

    dataI = $(this).data('i');

	$('div[id="div-' + dataI + '"]').addClass('h');

});

$('a.hover').mouseout(function() {

    dataI = $(this).data('i');

	$('div[id="div-' + dataI + '"]').removeClass('h');

});
a {
    display: inline-block;
    width: 100px;
    margin: 60px 20px 60px 0;
    text-align: center;
}

div {
    display: inline-block;
    width: 100px;
    height: 100px;
    margin-right: 20px;
    background-color: #ddd;
}

div.h {
    background-color: #f00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<a class="hover" data-i="1">DIV 1</a>

<a class="hover" data-i="2+">DIV 2+</a>

<a class="hover" data-i="3">DIV 3</a>

<br />

<div id="div-1"></div>

<div id="div-2+"></div>

<div id="div-3"></div>
like image 136
Alexander O'Mara Avatar answered Sep 28 '22 23:09

Alexander O'Mara