Search Text and Replace with JavaScript - javascript

Example I've this code:
<div class="description"> I make you smile. </div>
Transformed to:
<div class="description"> I make you think. </div>
Note: "smile" was replaced to "think"
How can I replace it, using javascript jQuery? It's possible to change several words?

var ele = $("div.description"); //Let ele be target element
ele.html(ele.html().replace(/smile/gi,"think")); //Replace the word in string,
// then put it back in.
.replace: MDN
Demo: http://jsfiddle.net/DerekL/FdyEH/

Related

How to use javascript to find and replace a word split in a few tags?

I want to use javascript to find and replace a word which has been split in a few tags.
For example, the html code:
<html>
<body>
<div id="page-container">
This is an apple.
<div>
<span>a</span><span>p</span><span>ple</span>.
</div>
</div>
</body>
</html>
And the it looks like below in the web browser:
This is an apple.
apple.
I use this javascript to find and replace the word "apple":
var a = document.getElementById('page-container').innerHTML;
a=a.replace(/apple/g,'pear');
document.getElementById('page-container').innerText=a;
But the result in the web browser is very bad, and all the tags could not work:
This is an pear.
<div>
<span>a</span><span>p</span><span>ple</span>.
</div>
It seems the replace function worked for the first row but cannot recognize the word split in the tags. This is an example, the whole content could be much more complex with more tags like , , not only ... Is there a way to replace only text but keep the original html tag format?
var a = document.getElementById('page-container').textContent;
a = a.replace(/apple/g, 'pear');
var a=a.split('.');
document.getElementById('page-container').innerHTML = `${a[0]}.<br/><span> ${a[1]}
<span>`;
That is because you have nested elements, so when you set innerHTML of the parent div, it treats inner div as text and print it out , try to replace this :
document.getElementById('page-container').innerText=a;
with this :
document.getElementById("page-container").firstChild.innerHTML = a;
So, you target only your first child which is parent div.
Live example:
https://jsbin.com/hujurageya/edit?html,js,output

Javascript:: textContent/innerText of firstChild

My code is pretty much explain itself of what I'm about to get :
<div id=player>
<div class="button hand">►</div>
<div class=time>00:00/02:25</div>
<div class="timeline hand"><span class="now hand"></span></div>
</div>
<script>
var myPlayer=document.getElementById('player').firstChild;
var playerStatus=(myPlayer.innerText||myPlayer.textContent);
console.log(playerStatus);
</script>
I'm expect to get the ascii value ► on console.
Small tweak needed here
Try this:
var myPlayer=document.getElementById('player').firstElementChild;
The problem is that the first child of #player is a text node itself. What you're looking for is the first element child of #player.
A minor note: firstElementChild isn't supported by IE8-.
You have both id and class available, so use querySelector().
var myPlayer=document.querySelector('#player > .button.hand');
This also has the benefit of working in IE8.
Also, a shortcut for innerText/textContent is to check for it at the top of your script, and store the appropriate key in a string.
var text = ("textContent" in document) ? "textContent" : "innerText";
Then use square brackets with the text variable.
var myPlayer=document.querySelector('#player > .button.hand');
var playerStatus=(myPlayer[text]);
Then you can actually shorten it like this:
var playerStatus=document.querySelector('#player > .button.hand')[text];

Remove div and its content from html string

Lets say i have a string like this:
<div id="div1"></div>
<div class="aClass" id="div2">
<div id="div3" class="anotherClass"></div>
<div id="div4" />
</div>
<div id="div5"></div>
I want to remove div2 from the string and everything inside that div
So i got a string like this
<div id="div1"></div>
<div id="div5"></div>
I thinking something like using regex to find the first div with the id of "div2" or whatever the id of the div is and count brackets untill it gets to "< /div>". The problem is that the "div3" also got a "< /div>" at the end.
The content of the div i want to remove may contain more or less div's then this too.
Any ideas on how to code this?
Update:
var htmlText = editor3.getValue();
var jHtmlObject = jQuery(htmlText);
jHtmlObject.find("#div2").remove();
var newHtml = jHtmlObject.html();
console.log(newHtml);
Why doesn't this return anything in the console?
Update2!:
I have made a jsFiddle to make my problem visual..
http://jsfiddle.net/WGXHS/
Just put the string into jQuery and use find and then remove.
var htmlString = '<div id="div1"></div>\
<div class="aClass" id="div2">\
<div id="div3" class="anotherClass"></div>\
<div id="div4" />\
</div>\
<div id="div5"></div>';
var jHtmlObject = jQuery(htmlString);
var editor = jQuery("<p>").append(jHtmlObject);
editor.find("#div2").remove();
var newHtml = editor.html();
If you have access to jQuery and your HTML is part of the DOM you can use $.remove()
EG. $('#div2').remove();
If it's not part of the DOM, and you have it in a string, you can do something like:
$('#div2', $(myHTML)).remove();
jQuery .remove() will do
$("#div2").remove();
The regex option would work if you control generating the string so you can ensure things like order of the attributes and indentation. If not your best bet is to use an HTML parser. If you are working inside of a browser jQuery is a good option. If you are working server-side you'll need to find a parser for the language you chose.

jquery html() and append() not working

for some reason both methods results are TextNode. It means that browser doesnot parse content of appended string.
for example
var code = "<div><p>Some</p> words are <span>here</span></div>"
$("#news_details").append(code);
on the page I do have content
"<div><p>Some</p> news are <span>here</span></div>"
this
$("#news_details").contents()
shows that string with html source is attached(for some reason unknown to me) as single textnode
but if will type in firebug
var text = $('#news_detaisl').text()
$('#news_details').contents().remove()
$('#news_details').append(text)
and after that, it is parsed and shows in a right way.
user the html()
var code = "<div><p>Some</p> words are <span>here</span></div>"
$("#news_details").html(code);
Since you haven't asked a question directly I can only assume what you want. Try this and tell me if it helps and if it was what you wanted:
var code = "<div><p>Some</p> words are <span>here</span></div>"
$("#news_details").append($(code));
Oh and $().append and $().html do NOT behave in the same way. $().append adds the input as a new child while $().html either returns the innerHTML of an element or sets it. Depending on whether you set a parameter.
only this code works fine, but such a weird behavior
var content = news.newsDetails(here async ajax request which load html snippet with content); //content is a string with html snippet from server
$("#news_content").append(content);
var value = $(".news_title").text();
$(".news_title").contents().remove();
$(".news_title").append(value);
$(".news_details").css('display','block')
and html snippet
<div class="news_details">
<img class="pointer" src="/static/img/close6.png" alt="close" width='16' height='16'>
<div class="news_head gradient">
<span>{{ item.pub_date|date:"d M Y" }}</span>{{ item.title }}
</div>
<div class="clear"></div>
<div class="news_title">{{ item.full_text }}</div>

Remove all HTML between two points

I would like to know how to remove all the HTML between two strings in a webpage. The webpage will not always have the same content, so this must work no matter what the two strings are and what their positions are. For example,
<div class='foo'>
<div class='userid'>123</div>
<div class='content'>
asdfasdf
</div>
</div>
<div class=bar>
<div class='userid'>456</div>
<div class='content'>
qwerqwer
</div>
</div>
How could I remove all the HTML between 'asdfasdf' and '123'?
Thanks
This is ugly but it works:
​var container = $("#cont");
var text = container.html();
var arr = text.split("asdfasdf");
arr[1] = "";
arr = arr.join("");
$("#cont").html(arr);
I added a container div. You could use the body tag or something else. Its possible with a regex as well.
Here is a working demo http://jsfiddle.net/QJSJH/.
Edit
I see the post changed quite a bit, but you could use the same concept as above.

Categories

Resources