user10279127
user10279127

Reputation:

Find div id in string and delete the whole div

I have a string with some DOM HTML saved inside, among which a div with static id="myId", which has no innerHTML but has dynamic width value set.

Example:

myString = "<div class="class">blahblah</div><div id="myId" width="42.584px"></div>"

How can I create a new identical string cutting off the whole <div id="myId" width="42.584px"></div>? The problem is that width="" value changes all the time so I can't do a .replace.

the HTML saved in the string, looks something like this (and number of divs can vary, but obviously only one has the myId div mentioned):

<div id="firstId"></div>
<div id="div0" class="div-class">
<span class="" onclick="clickFunctionTwo()">text div 0</span>
<span class="" id="fasdf"></span>
<span id="btnClose"><img src="close.svg" class="" onclick="clickFunction()"></span>
<div id="myId" class="" style="width: 59.5312px;"></div>
</div>
<div id="div1" class="div-class">
<span class="" onclick="clickFunctionTwo()">text div 1</span>
<span class="" id="eyuacv"></span>
<span id="btnClose"><img src="close.svg" class="" onclick="clickFunction()"></span>
</div>
<div contenteditable="true" id="lastId" style="height:18px;" onkeydown="myFunction()"></div>

Upvotes: 0

Views: 485

Answers (2)

Jeto
Jeto

Reputation: 14927

You could create a jQuery element from that string, remove the #myID div then grab the new HTML:

var myString = `
  <div id="firstId"></div>
  <div id="div0" class="div-class">
    <span class="" onclick="clickFunctionTwo()">text div 0</span>
    <span class="" id="fasdf"></span>
    <span id="btnClose"><img src="close.svg" class="" onclick="clickFunction()"></span>
    <div id="myId" class="" style="width: 59.5312px;"></div>
  </div>
  <div id="div1" class="div-class">
    <span class="" onclick="clickFunctionTwo()">text div 1</span>
    <span class="" id="eyuacv"></span>
    <span id="btnClose"><img src="close.svg" class="" onclick="clickFunction()"></span>
  </div>
  <div contenteditable="true" id="lastId" style="height:18px;" onkeydown="myFunction()"></div>`;

var myNewString = $('<div>').append(myString).find('#myId').remove().end().html();

console.log(myNewString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

Gabbr Issimo
Gabbr Issimo

Reputation: 111

Maybe you can try do build that string in another way,like:

var myArray = [
  "<div class="class">blahblah</div>",
  "<div id="myId" width="42.584px"></div>"
]

And you can build the string with:

var myString = myArray.join("")

And make the changes on myArray[0...n]. So removing a single array position its like removing a div.

Upvotes: 0

Related Questions