I have html code(that i get from an ajax call) in a javascript string that i want to manipulate. If the div coming already exists in the string, i want to remove it or want to change its content.
For example i have this code in a string:
<div id ="message_abc_support" class = "messageclass">
<div class="messageBlockImage2">
</div>
<div id="messageBlockText">
<div id="messagesname">abc</div>
<div id="messagesmsg">123</div></div></div>
<div id ="message_abcd_support" class = "messageclass">
<div class="messageBlockImage2">
</div>
<div id="messageBlockText">
<div id="messagesname">abcd</div>
<div id="messagesmsg">123</div></div></div>
now suppose i get from an ajax call:
<div id ="message_abcd_support" class = "messageclass">
<div class="messageBlockImage2">
</div>
<div id="messageBlockText">
<div id="messagesname">abcdef</div>
<div id="messagesmsg">123456</div></div></div>
how do i replace the other div with the same id? Please note i have this in a string so i cant just remove the div
I feel like my teacher who told us "Well, I've been teaching them Algebra for 30 years, I figured it's about time they started getting it".
To get to the point: Regular expressions are insufficient in strength to parse arbitrary HTML. There are a lot of edge cases and rules that cause bugs.
There are however ways to otherwise easily solve your problem:
The correct approach is to not have duplicate IDs to begin with. Seriously, there is almost never a good reason to have duplicate IDs. They are by definition unique. Simply do not add IDs to the divs in the first place. If you need to query for them consider for a minute what you're doing: You're querying your visual presentation for business information. Instead, use arrays and objects to represent your actual data and bind them to the presentation (with a closure or explicit mapping for example).
But... you already have this code.. And learning about proper UI structuring can take a lot of time.. And maybe you're not even the one creating this code on the backend.
So, you can use the built in DOM parsing abilities every browser has:
var el = document.createElement("div"); // placeholder
el.innerHTML = response; // feed your AJAX response there
var elms = el.querySelectorAll("[id]"); // select every element with an ID attribute
for(var i = 0; i < elms.length; i++){
// check if element with the same ID exists in the document
if(document.querySelector(elms[i].id)){
// wipe the ID out, in your code you can do whatever with it
elms[i].id = "";
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments