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>
id
s must start with a letter (w3.org/TR/html4/types.html#type-id) with HTML5 you can use numbers. Either change yourid
s to start with a letter or use HTML5getElementById
returns the typeElement
, whilequerySelector
returns the typeHTMLElement
. Sometimes only one of them is applicable in certain contexts. Please find more details here, here, and here