0

I am trying to use jQuery .attr function to add multiple ids to an element. However I found out that if I have multiple ids in the .attr function the function error out.

This doesn't cause error

This cause error

Error Code

var some_global = 0;

$('#btnName').click(function(){

    var k = $("<label>", {html: "->label"});

    $('<li>', {html: "list"})
      .attr("id", some_global + " error") // adding multiple id cause error
      .css("display"," block")
      .appendTo('ul.justList')


    k.appendTo("li#"+some_global);    

    some_global += 1;    

});

I briefly scanned the documentation and it seems like this isn't necessary a forbidden usage. Can someone point me a direction?

user445670
  • 179
  • 8
  • 1
    There's no such thing as multiple IDs. Elements have a single ID that isn't shared on the page. –  Sep 10 '15 at 17:51
  • 1
    However, I don't get any error in Chrome. It seems like you're only trying to create *unique* ids. So why not just do `"error" + some_global`, then select `"li#error" + some_global`? –  Sep 10 '15 at 17:52
  • 2
    Id's [cannot contain space characters](http://www.w3.org/TR/html5/dom.html#the-id-attribute), it looks more like you are wanting to add classes not ids – Patrick Evans Sep 10 '15 at 17:54
  • Why do you need more than one id? You can use `.attr('data-id')` or `.data('id')` – Ragnar Sep 10 '15 at 17:55
  • http://jsfiddle.net/J5nCS/677/ - remove space(s), and you are good to go.... – sinisake Sep 10 '15 at 18:14

1 Answers1

1

Having multiple id's per element is not valid HTML reference answer

In XML, fragment identifiers are of type ID, and there can only be a single attribute of type ID per element. Therefore, in XHTML 1.0 the id attribute is defined to be of type ID. In order to ensure that XHTML 1.0 documents are well-structured XML documents, XHTML 1.0 documents MUST use the id attribute when defining fragment identifiers on the elements listed above. See the HTML Compatibility Guidelines for information on ensuring such anchors are backward compatible when serving XHTML documents as media type text/html.

In order to get this behavior, you should use classes.

$("#some_element_id").addClass("error");
Community
  • 1
  • 1
SLAF
  • 51
  • 1
  • 4