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

+3


source to share


4 answers


If you only want to keep one child .infodiv

, this :not

is a good choice. Otherwise, consider the method filter()

.



+2


source


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>
      

Run codeHide result


+1


source


Try this: -

$('.infodiv p:not(#111)').remove();

      

0


source


id

HTML element cannot start with numbers [0-9]

6 Basic HTML data types

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);
      

Run codeHide result


0


source







All Articles