29

I'm trying to create a way to edit a bunch of comments and identify them by some id that I can generate. The errors I'm having is that there is:

SyntaxError: Failed to execute 'querySelector' on 'Document': '#1234' is not a valid selector. However, I don't see how this is possible since I clearly have id=1234 in the <p>.

Additionally, there are issues where when I comment everything else and do an alert(id), this does not work for the second form and the error is that:

TypeError: Cannot read property 'classList' of null.

Here is it in jfiddle: https://jsfiddle.net/wafqgq0L/2/

document.querySelector('.editable').addEventListener('click', function(event) {
 var index = event.target.id.indexOf('_');

 var id = event.target.id.substring(0,index);
	
	//actual data
	document.querySelector('#'+id).classList.add('hidden');
  
  //edit button
  document.querySelector("#"+id+"_edit").classList.add('hidden');
  
  //textarea
	document.querySelector("#"+id+"_editable").classList.remove('hidden');
  
  //save button
	document.querySelector("#"+id+"_save").classList.remove('hidden');

});
.hidden {
  display: none;
}
//all id will be like 12345_comment

<div class="editable">
<p id="1234">
  Some comment
</p>

<form action="form.php" method="post">
  <textarea id="1234_editable" class="hidden">Some comment</textarea>
  <a href="#" id="1234_edit">Edit</a>
  <a href="#" id="1234_save" class="hidden">Save</a>
</form>
</div>
<br><br>
<div class="editable">
<p id="123">
  Some comment
</p>

<form class="editable" action="form.php" method="post">
  <textarea id="123_editable" class="hidden">Some comment</textarea>
  <a href="#" id="123_edit">Edit</a>
  <a href="#" id="123_save" class="hidden">Save</a>
</form>
</div>

4
  • 8
    If using HTML4 ids must start with a letter (w3.org/TR/html4/types.html#type-id) with HTML5 you can use numbers. Either change your ids to start with a letter or use HTML5
    – blurfus
    Jan 13, 2016 at 21:40
  • Is there a reason you cannot use JQuery? it makes DOM manipulations like this much easier (and with more succinct syntax)
    – blurfus
    Jan 13, 2016 at 22:08
  • 3
    Don't understand why you're not using getElementById Jan 13, 2016 at 23:09
  • 2
    @SteveHarris I know this is an old question, but maybe other viewers could find interesting that getElementById returns the type Element, while querySelector returns the type HTMLElement. Sometimes only one of them is applicable in certain contexts. Please find more details here, here, and here Apr 12, 2020 at 5:50

4 Answers 4

40

If using HTML4 ids must start with a letter (https://www.w3.org/TR/html4/types.html#type-id)

If using HTML5 you can use numbers.

Either change your ids to start with a letter (as in id="p12345") or use HTML5 (i.e. use <!DOCTYPE html> at the top of your document)

6
  • I changed it, but still have this error: Uncaught TypeError: Cannot read property 'classList' of null: jsfiddle.net/wafqgq0L/4 That did not save changes, sec.
    – user4634820
    Jan 13, 2016 at 21:47
  • Your code does not do anything when clicking on the save button - can you post that part of the code?
    – blurfus
    Jan 13, 2016 at 21:51
  • jsfiddle.net/wafqgq0L/10 Updates. The upper form works now, but the bottom does not. The save button should not do anything right now. I just want the textarea to appear. Also nothing in the console
    – user4634820
    Jan 13, 2016 at 21:52
  • You get the error "Uncaught TypeError: Cannot read property 'classList' of null" when you click outside of the link (i.e. on the div) since the 'target' does not have an id... I will try to add a fuller solution
    – blurfus
    Jan 13, 2016 at 21:57
  • 4
    Actually, document.querySelector('#000") does throw an error whatever the DocType of the document. Interesting question...
    – Kaiido
    Jan 18, 2016 at 9:40
11

You can use template string literals for this because id must be in quotes otherwise it won't work and be sure to use HTML5 at the top of your document. With this I didn't have any more issues.

For example:

document.querySelector(`[data-id="${id}" ]`);

Or if for any reason you don't want to use template literals add this line of code:

document.querySelector("[data-id=" + "\'" + id + "\'" + "]");

With escape character \' in double quotes.

Hope this helps.

0
4

You might find jQuery easier, and it's automatically cross-browser (and faster to type!) Since it's tagged on your question, here is the jQuery solution:

Edit: The tag jQuery was removed from the original question on May 25 '19 at 21:10 (3 years after question was asked and answered), by user John, with the inexplicable editor comment "remove spam tags".

jsFiddle Demo

$('[id^=edit_]').click(function(){
    var id = this.id.split('_')[1];
    $('#'+id).addClass('hidden');
    $('#edit_'+id).addClass('hidden');

    $('#save_'+id).removeClass('hidden');  
    $('#editable_'+id).removeClass('hidden');  
});

$('[id^=save_]').click(function(){
    var id = this.id.split('_')[1];
    $('#'+id).removeClass('hidden');
    $('#edit_'+id).removeClass('hidden');

    $('#save_'+id).addClass('hidden');  
    $('#editable_'+id).addClass('hidden');  
});

Note that I switched around the id_number and the idName_ prefix. This makes it much easier to target those elements using the starts with selector: id^=

3
  • This is great. Thanks. Do you know if I can make a post request after Save is clicked?
    – user4634820
    Jan 13, 2016 at 22:09
  • 1
    What you are looking for is called AJAX - and don't be intimidated, it's much easier than it sounds. See this post and this answer for a quick introduction, and as always on StackOverflow, please upvote any posts that you find helpful.
    – cssyphus
    Jan 13, 2016 at 23:47
  • 3
    That does provide a workaround, but doesn't explain why document.querySelector('#000') does throw an error while document.querySelector('[id="000"]') retrieves the element just as document.getElementById('000') does...
    – Kaiido
    Jan 18, 2016 at 9:37
1

document.querySelector("class or id") is not using tags as arguments instead it uses class or Id.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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