简体   繁体   中英

Javascript find and replace dom string

I want to use replace method of javascript to replace some html string. I stored a dom string by fetching .outerHTML and want to replace a perticular word with the string. Here is my outerHTML dom which i fetch with javascript :

<figure class="image" onclick="someMethod('btbjwkjpuynyzdijsvf5.jpg', 'Title','$caption', 'image','other params')">
    <img id="45435435345" src="btbjwkjpuynyzdijsvf5.jpg" caption="$caption" title="title">
    <figcaption>$caption</figcaption>
</figure>

Here is want to replace all $caption with real caption which i fetch from database later. But this is not working. I tried on browser console to store this string on variable but it giving error after single quote (which is available inside function parameter). So i think it is having a problem with unrecognized string value. How can i resolve this issue so i can replace $caption value from string.

This is not a good practice but instead you can use a javascript templating engine

 $("#myDiv").html($("#myDiv").html().replace(/\\$caption/g,'My caption'));
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="myDiv"> <figure class="image" onclick="someMethod('btbjwkjpuynyzdijsvf5.jpg', 'Title','$caption', 'image','other params')"> <img id="45435435345" src="btbjwkjpuynyzdijsvf5.jpg" caption="$caption" title="title"> <figcaption>$caption</figcaption> </figure> </div>

I would use the attribute selector

$("[caption]").attr("caption", myCaptionText)

you should ofcourse be a bit more specific so you don't over write every instance of the caption attribute

$(".specificParent [caption]").attr("caption", myCaptionText)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM