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?

5
  • 1
    There's no such thing as multiple IDs. Elements have a single ID that isn't shared on the page. Commented Sep 10, 2015 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? Commented Sep 10, 2015 at 17:52
  • 2
    Id's cannot contain space characters, it looks more like you are wanting to add classes not ids Commented Sep 10, 2015 at 17:54
  • Why do you need more than one id? You can use .attr('data-id') or .data('id') Commented Sep 10, 2015 at 17:55
  • jsfiddle.net/J5nCS/677 - remove space(s), and you are good to go.... Commented Sep 10, 2015 at 18:14

1 Answer 1

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");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.