0

I have divs with ids as below:

<div id="text.header" class="countDiv"></div>
<div id="text.content" class="countDiv"></div> etc

I have two arrays. In the first i have, array1 = [1,2] and in the other I store the ids of all the divs using the following snippet

$(".countDiv").each(function(i){
    array2[i] = $(this).attr("id");
}

then I use .html() to write the value of i into the id of the div by using:

for(var myCount = 0; myCount < array1.length; myCount++){
    $("#" + array2[i]).html(array1[i]);
}

The problem is that for all cases its fine, but when i use . in between the ids, the code doesn't work. No error is showed on the console.

eg: when i use , , it works well, but when i use , the page is blank. The code doesn't work.

Am I doing something wrong here? Any help is appreciated.

DarkThrone
  • 1,954
  • 1
  • 14
  • 14
Sudeep
  • 109
  • 7
  • 1
    Think about what `$("#test.header")` will select, considering `.` usually precedes a classname. – Kevin B Jun 06 '13 at 05:20

4 Answers4

2

If you look at what your resulting selector string will look like, you'll see the problems that this line causes:

$("#"+array2[i])

Let's say the id is text.header. Look at what the resulting selector string becomes:

$('#text.header')

This selector will match an element with an id of text and a class of header. That's not what you want. The jQuery solution would be to escape the dot, but a better way would be to just use the native DOM method and wrap it in a jQuery object:

$(document.getElementById(array2[i]))

I didn't see this approach listed in the duplicate question, so I might as well post it here.

Blender
  • 289,723
  • 53
  • 439
  • 496
1

You have mentioned myCount and didn't use it. Also jquery creates problem while using . in id so use javascript here for selecting id

var array2=new Array();
var array1 = [1,2];
$(".countDiv").each(function(){
   array2.push($(this).attr("id"));
});

for(i=0; i<array1.length; i++){
    document.getElementById(array2[i]).innerHTML=(array1[i]);
}

Fiddle http://jsfiddle.net/gEScc/1/

Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
0

The . represents a class selector in jQuery (and CSS). Consider escaping it to \.

$("#" + array2[i].replace(".", "\\."))...
JNF
  • 3,696
  • 3
  • 31
  • 64
-1

.Yes.

'.' is the class path separator in CSS and therefore and obviously can not be used in class names.

Thats by design (CSS).

Axel Amthor
  • 10,980
  • 1
  • 25
  • 44
  • 2
    OP is using it in an id attribute, which is fine. – Blender Jun 06 '13 at 05:18
  • Yes. But jQuery recognises it as a class name separator: http://stackoverflow.com/questions/605630/how-to-select-html-nodes-by-id-with-jquery-when-the-id-contains-a-dot – Axel Amthor Jun 06 '13 at 05:20