Hey appreciate any help I can get with this as I'm still learning JavaScript.
I have some HTML that I'm trying to insert specific span tags into. I've found answers that allow you to just replace inner HTML, however the content I'm trying to wrap around is slightly different on each page I'm trying to achieve this for - but the HTML structure is the same.
Here is the current HTML, vs what I would like it to be:
<div class="list-view__count">
<p>
Showing 1 - 18 of 46 results
</p>
</div>
And what I'd like to add in:
<div class="list-view__count" content="nosnippet">
<p>
<span data-nosnippet>Showing 1 - 18 of 46 results</span>
</p>
</div>
I have tried various codes and successfully added the content="nosnippet" section,
document.querySelector(".list-view__count ").setAttribute("content", "nosnippet")
but the tag I can't seem to figure out how it is done yet.
Any help will be appreciated.
Cheers
try something like
var div = document.getElementById('list-view__count');
var x = document.creatElement('span');
var text = document.createTextNode('text here');
x.appendChild(text)
div.appendChild(x)
<p> with textContent, save it in a variable, then create a span tag and set the text to the <span> with the same method.data... attribute without a value like that, but functionally it should be the same.const div = document.querySelector(".list-view__count");
const p = document.querySelector(".list-view__count>p");
const pText = p.textContent;
const span = document.createElement("span");
div.setAttribute("content", "nosnippet")
p.textContent = '';
span.textContent = pText;
span.setAttribute("data-nosnippet", '')
p.appendChild(span);
console.log(document.querySelector(".wrap").outerHTML)
<div class="wrap">
<div class="list-view__count">
<p>
Showing 1 - 18 of 46 results
</p>
</div>
</div>
You can select the p element that is the immediate child of your div, pick up its innerHTML (I did this just in case it had some HTML mark up in it so that is preserved), clear the innerHTML of the p element then append a span element which has the data- attribute set and the innerHTML copied from the original p.
const p = document.querySelector('.list-view__count > p');
const pInner = p.innerHTML;
p.innerHTML = '';
const span = document.createElement('span');
span.innerHTML = pInner;
span.setAttribute('data-nosnippet', '');
p.append(span);
<div class="list-view__count">
<p>
Showing 1 - 18 of 46 results
</p>
</div>