问题
I have the following script that makes an HTML page editable
document.body.contentEditable = 'true'; document.designMode='on';
I am wanting to only allow my users to edit sections with a class of "edit". Is this possible?
回答1:
YOu can try to find all the elements with the class name 'edit' and change all off them like below.
document.querySelectorAll('.edit').forEach(function(element){
element.contentEditable = 'true';
})
回答2:
Yes that's possbile.
let el_array = document.getElementsByClassName('edit');
Then loop on el_array and apply this to each element el.contentEditable = true;
回答3:
Yes this is possible, just run a simple loop over all elements with the edit class and give them contentEditable true
[...document.getElementsByClassName("edit")].forEach(
el => el.contentEditable = "true"
);
Thats all!
Edit: as harry mentioned in the comments: forEach doesnt work on htmlCollection objects, so you must cast it to an array using [...theHTMLCollection]
回答4:
function edit_content(){
document.querySelectorAll('.myP').forEach(function(ele){
ele.contentEditable = 'true';
})
}
<p class="myP">
abcdefghijklmnop
</p>
<button onclick="edit_content()">
Click to edit
</button>
you can do this. first, select all classes in the DOM by querySelectorAll
then iterate that from forEach
loop.
来源:https://stackoverflow.com/questions/64389650/javascript-contenteditable-of-certain-classes-only