How do I target all •
items in html code?
For Example I have this html code
<p>• sentence with bullet in front of it</p>
<p>• second sentence with bullet in front of it</p>
and i want to use this code below using html.replace to replace the •
string with an empty quotes.
Not sure if im using regex the right way? thanks for your help!
function replaceBullets(html) {
return html.replace(/•/, ""); //not sure if im writing these inputs correctly
}
CodePudding user response:
<body>
<div id="sectionToClear">
<p>• sentence with bullet in front of it</p>
<p>• second sentence with bullet in front of it</p>
<p>• second sentence with bullet in front of it</p>
<p>• second sentence with bullet in front of it</p>
</div>
<script>
function replaceAllBulls() {
let section = document.querySelector('#sectionToClear');
section.innerHTML = section.innerHTML.replace(/\u2022/g, "");
}
replaceAllBulls();
</script>
</body>
You can look for a div with id, for example sectionToClear
and get it's inner HTML, then replace •
char (or \u2022
) with "nothing". And don't forget to add /g
(global)! If you don't add it, it will delete only the first item.
Also, you have wrong function syntax. Look at JS docs to learn more.
CodePudding user response:
This will work as well as using the character code, which is \u2022
!
function replaceBullets() {
const pElements = document.getElementsByTagName("p")
for (let element of pElements) {
element.innerText = element.innerText.replace(/(•|•)/g, "")
}
}
<body onl oad="replaceBullets()">
<p>• sentence with bullet in front of it</p>
<p>• second sentence with bullet in front of it</p>
</body>
You can view how the regex works here.