Reputation: 8134
I have this JS string:
"<div>
<p id='foo'>foo text</p>
<p id='bar'>bar text</p>
<p id='sol'>sol text</p>
</div>"
And I want to replace only the paragraph id 'bar' and return all the string with the new modifcation. How can I do this? I know I can use a regex, however if I can avoid it, it would be better I think...
I have tried to convert the string to a DOM object like this:
var str = "<div><p id='foo'>foo text</p><p id='bar'>bar text</p><p id='sol'>sol text</p></div>"
and then,
var dom_str = $(str);
however I don't know how to select the bar id and return all the string.
The output I want to get is the following for this example:
var result = "<div><p id='foo'>foo text</p><p id='bar'>new text here</p><p id='sol'>sol text</p></div>"
Any help will be greatly appreciated.
Upvotes: 0
Views: 74
Reputation: 19725
on the jQuery object
(it's not a dom element) do $obj.find('#bar').text('new text here')
var str = "<div><p id='foo'>foo text</p><p id='bar'>bar text</p><p id='sol'>sol text</p></div>"
var $obj = $(str);
$obj.find('#bar').text('new text here')
note: it's better to save the parsing in a variable $obj
because if you need more work on that object you don't have to parse it every time.
Upvotes: 2
Reputation: 288680
Try this:
var str = "<div><p id='foo'>foo text</p><p id='bar'>bar text</p><p id='sol'>sol text</p></div>",
el = document.createElement('div');
el.innerHTML = str;
el.querySelector('#bar').textContent = "new text here";
var result = el.innerHTML;
Upvotes: 2