I want to change the innerHTML of .container in real-time via setAttribute('data-content', 'value changed');. Currently, I am appending innerHTML via .container.innerHTML = .container.getAttribute('data-content');
const container = document.querySelector('.container');
container.innerHTML = container.getAttribute('data-content');
const btn = document.querySelector('.btn');
// before clicking on button
console.log(container.getAttribute('data-content'));
btn.addEventListener('click', (e) => {
container.setAttribute('data-content', 'Value Changed!!');
console.log(container.getAttribute('data-content'));
});
* {
margin: 0;
padding: 0;
outline: 0;
box-sizing: border-box;
}
body {
height: 100vh;
display: flex;
padding-top: 1rem;
align-items: flex-start;
justify-content: center;
}
.btn {
cursor: pointer;
margin-left: 1rem;
padding: 0.25rem 0.5rem;
}
<div class="container" data-content="Hello, World!"></div>
<button class="btn">Change Attribute Value</button>
It is exactly as folks in comments said - You could create this binding with using some kind of "JS framework", where you would define binding between the attribute and the "value HTML/text value of <div> tag.
But in the plain JS/html, you have to set this value manually.
const container = document.querySelector('.container');
container.innerHTML = container.getAttribute('data-content');
const btn = document.querySelector('.btn');
// before clicking on button
console.log(container.getAttribute('data-content'));
btn.addEventListener('click', (e) => {
container.setAttribute('data-content', 'Value Changed!!');
console.log(container.getAttribute('data-content'));
// Added line
container.innerHTML = container.getAttribute('data-content');
});
* {
margin: 0;
padding: 0;
outline: 0;
box-sizing: border-box;
}
body {
height: 100vh;
display: grid;
place-items: center;
}
.btn {
cursor: pointer;
padding: 0.25rem 0.5rem;
}
<div class="container" data-content="Hello, World!"></div>
<button class="btn">Change Attribute Value</button>
You can use attr function in CSS for pseudo element
const container = document.querySelector('.container');
const btn = document.querySelector('.btn');
// before clicking on button
console.log(container.getAttribute('data-content'));
btn.addEventListener('click', (e) => {
container.setAttribute('data-content', 'Value Changed!!');
console.log(container.getAttribute('data-content'));
});
* {
margin: 0;
padding: 0;
outline: 0;
box-sizing: border-box;
}
body {
height: 100vh;
display: grid;
place-items: center;
}
.btn {
cursor: pointer;
padding: 0.25rem 0.5rem;
}
.container::before{
content: attr(data-content);
}
<div class="container" data-content="Hello, World!"></div>
<button class="btn">Change Attribute Value</button>