+ 2
How do you add an attribute to an h1 tag using JS onclick attribute?
I wanna add the "contenteditable" attribute to an h1 tag on the click of an image. Pls help meeeeee. https://code.sololearn.com/WgDnf24280i3/?ref=app
3 Antworten
+ 3
The following will work for you:
function edit() {
var h1 = document.querySelector("h1");
var set = h1.setAttribute("contenteditable", "true");
}
When I looked at your code, that edit function was triggered by the click of a checkbox instead of an image but I'm sure you can handle listening to an image's click instead of the checkbox.
The main things I fixed were:
- fixed your document query. You had document.getElementById("h1") but h1 is the tag name and not an id attribute value. document.querySelector works instead.
- in setAttribute, added a second parameter "true" because you need to specify 2 parameters to setAttribute. You might also get away with not using setAttribute and setting it like this: https://www.w3schools.com/jsref/prop_html_contenteditable.asp
- removed the "addAttribute" call since that method doesn't exist on document Element's.
+ 3
How do I remove the attribute when I click it again?
+ 1
If you ever want to remove the attribute, call the removeAttribute method.
For example:
function toggleContentEditable() {
var h1 = document.querySelector("h1");
if (h1.hasAttribute("contenteditable"))
h1.removeAttribute("contenteditable");
else
h1.setAttribute("contenteditable", "true");
}
More explanation and code examples are at:
https://www.w3schools.com/jsref/met_element_removeattribute.asp