8

The problem

I'm trying to change the inner HTML value of an element. I've not used jQuery really much and I'm still a novice in many aspects of its functionalities.

    $('a.toggle-download').live('click', function (event) { 
        $.post("/ajax/toggle-download", { code: $(this).data("document"), prev_value: $(this).data("val") })
        .done(function(data) {
            var json = data,
            obj = JSON && JSON.parse(json) || $.parseJSON(json);
            if(obj['return'] == 1){
                //document.getElementById("p_" + obj['code']).innerHTML = 'some text';
                $("#p_" + obj['code']).html('some text');
            }
        });
        event.preventDefault();
    });

I've tried both lines, first the jQuery one through $("#p_" + obj['code']), which did not work and then through document.getElementById("p_" + obj['code']) which works perfectly.

It seems I'm missing something obvious here, but still i don't understand why jquery does not work in this case!

The question

Why does the plain old javascript work correctly, when jQuery does not?

Additional informations

1) jQuery itself works and it's correctly loaded. No conflicts are present: the ajax call is sent successfully and the answer is correctly received,

2) The received ID exists and it's unique

3) I'm not keen on jQuery html() method but i followed the documentation and it should work as i used it

System information

This problem presents itself while using Chrome 27.0.1453.116 m. I didn't tested it with other versions or other browsers, but i'm quite sure to presume that's a jQuery problem rather than a browser problem. Also, i'm using php 5.3 on apache, but again these info should not be relevant to the problem.

If I missed some information you need to better understand my problem, please let me know in the comments and I'll try to answer you as soon as i can. Also, please forgive my bad grammar but I'm not a native english speaker.

Answers to comments

as requested, here's an example of the ajax response: {"return":1,"code":"5.43.321"}

the command console.log($("#p_" + obj['code']).length) yields "0"

STT LCU
  • 4,258
  • 4
  • 26
  • 47

4 Answers4

9

If Your id is p_x.xx.xxx then $('#' + id) means: element with the id p_x and classes xx and xxx.

Either replace the dots with \\. before using the string as id ore use the approach suggested by @dystroy.

a better oliver
  • 24,069
  • 2
  • 48
  • 59
  • Thank you. It seems to be the issue! – STT LCU Jul 01 '13 at 11:59
  • your answer is basically correct, but i need to replace the periods with `\\.` rather than `\.`! please, edit the answer :) – STT LCU Jul 01 '13 at 12:15
  • I spent so much time trying to figure out why it wasn't detecting my fields generated by asp.net-core and had a '.' on the id. Pretty much jQuery thought it was a class – Jackal Nov 07 '19 at 11:16
4

When you want to select an element using an arbitrary string as ID, you'd better avoid using a '#'+yourstring selector : in many cases this can make a selector invalid for jQuery even while your string is a valid HTML5 id.

If your id contains a dot, jQuery will interpret it as the start of a class.

Prefer this :

$(document.getElementById(yourstring))
Denys Séguret
  • 335,116
  • 73
  • 720
  • 697
  • This works, thank you. Can you please explain why does the approach `# + string` causes this wrong behavior? – STT LCU Jul 01 '13 at 11:51
  • 1
    The string has to be parsed and jQuery has to recognize the id part. But in HTML5 you can put > or # or so many characters in an id that many selectors can't be interpreted (to be more precise, you'd need to escape the characters specifically for the selector). – Denys Séguret Jul 01 '13 at 11:55
  • Thank you again for your answer. I've marked zeroflagL's one as accepted because it explained WHY the current selector was not working. Anyway your answer works perfectly and i gave it a +1 – STT LCU Jul 02 '13 at 06:54
  • Well... I had explained it too... but no worry. – Denys Séguret Jul 02 '13 at 07:01
  • Yeah but you said that it may be interpreted as invalid, which is 100% correct, but did not say WHY it was invalid in this case :) – STT LCU Jul 02 '13 at 07:09
  • 1
    @STTLCU Read the comment above (the second one after the answer, made before you gave your exact id) and this sentence in my answer : `If your id contains a dot, jQuery will interpret it as the start of a class.`. But again, it doesn't really matter, I'm just surprised you found something more in the other answer that what I had already given in my answer or my comment. – Denys Séguret Jul 02 '13 at 07:29
3
$("[id='p_"+code+"']")

This will also work. It contains the periods in the id string.

Joe Frambach
  • 25,568
  • 9
  • 65
  • 95
  • My doctype is already as you specified. Anyway, thank you for your answer! – STT LCU Jul 01 '13 at 11:56
  • Sorry I realized that answer wouldn't help so I deleted it and tried something else. Didn't think anyone would notice oops – Joe Frambach Jul 01 '13 at 11:57
  • Thank you again for your answer. I've marked zeroflagL's one as accepted because it explained WHY the current selector was not working. Your answer got my personal second place, but i can't award it except for a simple +1. FYI, i'll probably end using this code in my project, if that's a consolation :D – STT LCU Jul 02 '13 at 06:55
2

This actually works for me...

<div id="p_testdiv1"></div>


var obj = { code : 'testdiv1' }

console.log(obj.code);

//document.getElementById("p_" + obj.code).innerHTML = "test"; // Also works

$("#p_" + obj.code).html("test1"); // Displays "test1" in the div

http://jsfiddle.net/hZ4yz/

Chris Dixon
  • 9,024
  • 5
  • 32
  • 66