Reputation: 47
I have been reading and studying about this library to be able to change the code of this codebox from jquery to javascript (https://codepen.io/mrWilson123/pen/OJMVwzd?editors=1010) but I got stuck in this part.
$(".slide-captions").html(function () {
return (
"<h2 class='current-title'>" +
currentTitle +
"</h2>" +
"<h3 class='current-subtitle'>" +
currentSubtitle +
"</h3>"
);
});
I understand that it's getting the div element and putting inner html code into it so I tried this but it didn't work.
document.querySelector(".slide-captions").innerHTML(
"<h2 class='current-title'>" +
currentTitle +
"</h2>" +
"<h3 class='current-subtitle'>" +
currentSubtitle +
"</h3>");
What am I doing wrong if someone could help me, thanks.
Upvotes: 0
Views: 63
Reputation: 29453
Whenever appending to the DOM
, there is a string-oriented approach using parse-able strings of HTML and properties and methods like:
.innerHTML
.insertAdjacentHTML()
There is also a construction-oriented approach using DOM Nodes and properties and methods like:
.insertBefore()
/ .before()
.appendChild
/ .append()
.insertAdjacentElement()
.classList
Whichever approach you normally use to build DOM, it's useful to be aware of the other approach:
let slideCaptions = document.querySelector('.slide-captions');
let myHTML = '';
myHTML += '<h2 class="current-title">' + currentTitle + '</h2>';
myHTML += '<h3 class='current-subtitle'>' + currentSubtitle + '</h3>';
slideCaptions.innerHTML = myHTML;
let slideCaptions = document.querySelector('.slide-captions');
let titleElement = document.createElement('h2');
titleElement.classList.add('current-title');
titleElement.textContent = currentTitle;
slideCaptions.appendChild(titleElement);
let subtitleElement = document.createElement('h3');
subtitleElement.classList.add('current-subtitle');
subtitleElement.textContent = currentSubtitle;
slideCaptions.appendChild(subtitleElement);
Upvotes: 1
Reputation: 872
Try this :
document.querySelector('.slide-captions').innerHTML=`
<h2 class='current-title'>" +
currentTitle +
"</h2>" +
"<h3 class='current-subtitle'>" +
currentSubtitle +
"</h3>`;
if there any error use this instead
document.querySelectorAll('.slide-captions')[0] // .innerHTML ....
Upvotes: 0