Store element by id in html string using javascript or jquery
I have a html line containing:
<div class="infodiv">
<p id="111"><span class="text">111</span></p>
<p id="222"><span class="text">222</span></p>
<p id="333"><span class="text">333</span></p>
</div>
I will put it in the content of the infowindow on Google Maps.
However, I want to remove some items by id before showing it in the infowindow.
For example: I only want to keep the element with id = 111.
So my html string will only show:
<div class="infodiv">
<p id="111"><span class="text">111</span></p>
</div>
Any ideas how I can achieve this?
thank
source to share
Can you use the :not
css selector in jQuery after use jQuery.parseHTML()
?
$(".infodiv p:not(#111)").remove();
console.log($(".infodiv").html())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="infodiv">
<p id="111"><span class="text">111</span><span></span></p>
<p id="222"><span class="text">222</span><span></span></p>
<p id="333"><span class="text">333</span><span></span></p>
</div>
source to share
id
HTML element cannot start with numbers [0-9]
ID and NAME must begin with a letter ([A-Za-z]) and can be followed by any number of letters, numbers ([0-9]), hyphen ("-"), underscore ("_"), colons (":") and periods (".").
Substitute the first number for a letter, for example "a"
in an attribute id
in HTML.
To convert HTML string to elements DOM
, you can set HTML to .innerHTML
element <template>
.
Create an array of the last part id
to be removed from the HTML string, iterate over the .children
parent element, call .removeChild()
with .querySelector()
, and the attribute ends with a selector, use .replace()
to remove unnecessary newline characters from the resulting HTML string.
const html = `<div class="infodiv">
<p id="111"><span class="text">111</span></p>
<p id="222"><span class="text">222</span></p>
<p id="333"><span class="text">333</span></p>
</div>`;
const template = document.createElement("template");
template.innerHTML = html;
const p = template.content.children[0];
const not = ["222", "333"];
for (let id of not) {
p.removeChild(p.querySelector(`[id="${id}"]`))
}
let parsedHTML = template.innerHTML.replace(/\n/g, "");
console.log(parsedHTML);
source to share