Javascript - Search through the HTML of a site and replace it? - javascript

Well, just like my title says.
Is it possible to search through a whole page's HTML/CSS, and then replacing certain strings using JavaScript?
I tried to make something on my own but I'm doing it wrong.
var i, sig = document.getElementsByClassName('signaturecontainer');
for (i = 0; i < sig.length; i++)
{
var str = sig[i].innerHTML;
var n = str.replace(/< div style='250px;overflow:scroll;'/g, "< div > style='height:100%'");
}
Why I want to replace the string instead of using .innerHTML and just editing is due to that the div I want to change does not have an ID/Class.
This is what the line(s) I need changed:
<!-- edit note -->
<blockquote class="postcontent lastedited">
Last edited by X; Today at <span class="time">06:32 AM</span>.
</blockquote>
<!-- / edit note -->
<div style="height:250px;overflow: auto;"> // <--- This one.
<blockquote class="signature restore"><div class="signaturecontainer">text here</div></blockquote>
</div>
</div>

This line will give trouble:
var new = str.replace(/< div style='250px;overflow:scroll;'/g, "< div > style='height:100%'");
new is a reserved word. Change it to newstr, or whatever.
Your regex pattern is unlikely to find anything: what it's searching for is not valid CSS
The string you want to insert is not valid HTML/CSS. It should probably be <div style='height:100%;'>
It occurs to me that if you're just tweaking the styling then this is a clumsy way to go. You can change the styling directly with Javascript.
var i, sig = document.getElementsByClassName('signaturecontainer');
for (i = 0; i < sig.length; i++)
{
sig[i].parentNode.style.height = "100%";
}

We'll no it is not impossible, with JavaScript you can parse an HTML document by locating the tags is that you are trying to change. For example
<div id="getThisChanged">change this text</div>
By executing this next line of JavaScript, you can change the text inside of the tag
document.getElementById('getThisChanged').innerHTML("text is now changed");
The text will be changed to "text is now changed"

Related

translate javascript/jquery to vba

I have this javascript/jquery code that deletes sections of a html file
var divs = document.getElementsByTagName('div');
var d = divs.length;
for (var i = 1; i < d; i++) {
if( $('.section'+i).innerHTML.includes("textfind")==true || $('.section'+i).innerHTML.includes("textfind2")==true){
$('.section'+i).remove();
}
}
I would like write the same function as vba code for word
I have this code so far
Dim i as Long
For each objSect in ActiveDocument.sections
if objSect.Range.Text like "textfind +i" Or "textfind2+i" then objSect.range.delete
Next objSect
how would I got about deleting those particular section where i find the strings
Can you please elaborate the question here?? And, you want to remove html or word elements using VBA??
EDIT :- You can create a variable and store an array of strings in it to find and replace. (note: If you want to just clear the text then, use an empty string in place of the 'replace' string.)
Refer to this link for VBA find and replace code VBA To find and replace a string in MS Word
RemoveTextfinders: will remove both of there elements
<div class="section1">textfind2</div>
<div class="section2"><input name="textfind2" value="" /></div>
But neither of these elements
<div class="section1" name="textfind2"></div>
<div class="">textfind2</div>
Sub RemoveTextfinders()
Dim d, divs
Set divs = document.getElementsByTagName("div")
For Each d In divs
If InStr(d.className, "section") And InStr(d.innerHTML, "textfind2") Then d.ParentNode.RemoveChild d
Next
End If
Update I combined the two if statements they where redundant.
InStr(d.className, "section") will evaluate to true if any of the div's class contain the "section".
This code ran fine for me. I must be mistaken about the structure of your html. Could you please post a sample of the html?

How can I insert text every n characters that isn't between two specific pieces of text?

I have html that I'm getting ready to insert into the dom. Before I do that, I need to insert the tag every 30 characters. This is very easy doing something like so:
var html = html.replace(/(.{30})/g, '$1<wbr>');
However, this simple solution often times will insert the tag into an existing html tag. For example, this could end up happening:
<spa<wbr>n> Some text here </span>
The html may be many children deep like so:
<div>
This is some text that we need to treat. <br />
<span> Here is some more text. Click here. </span>
</div>
What's the best way to approach this? Is regex a possible solution? Or do I need to write a javascript function? I was hoping I could figure out how to write a regular expression similar to the one above that inserts text every n characters UNLESS it's between the characters '<' and '>'.
Any help is appreciated.
Here is my solution. Normally I wouldn't want to use jquery but time is of the essence.
var el = $('<div>' + html + '</div>');
var allChildren = el.find('*');
allChildren.each(function() {
for(var i = 0, len = this.childNodes.length; i < len; i++) {
if(this.childNodes[i].nodeType === 3) {
var newHtml = this.childNodes[i].nodeValue.replace(/(.{30})/g, '$1<wbr>');
$(this.childNodes[i]).replaceWith(newHtml);
}
}
});
html = el.html();
You could use this:
(.{30}.*?\s)
Working regex example:
http://regex101.com/r/nL0qT2
Javascript:
var html = html.replace(/(.{30}.*?\s)/g, '$1<br />');
So this will insert the <br> tag on the next following space after the 30th character, so the <br> doesn't get inserted inside any word or tag.

How to remove or hide only visible text & link from website using java script

How to remove or hide only visible "text & link" from website using java script. For example I want to hide "some text " & "Link text here" from bellows code without remove this full code
<p style="text-align:center;">some text Link text here</p>
Please help me
Assuming you mean that you want to hide the <p> tag, you need this piece of JavaScript:
document.getElementsByTagName('p')[0].style.display = 'none';
That will hide the first <p> tag on your page. I suggest adding a class or id to the tags you want to hide though, so that you can select them more accurately.
If you want to clear all contents of your <p> tag, you can do this:
document.getElementsByTagName('p')[0].innerHTML = '';
That will simply remove all of the tag's contents. If you want to remove the whole tag itself (so that it doesn't leave the empty <p> tag sitting around) you can change the .innerHTML part to .outerHTML.
There are several things to consider: you may want the test to return, so we cannot just lose it. You may want to preserve event bindings on nested elements, so we cannot simply destroy those. In the end, I would suggest CSS being the most appropriate route to take.
var paragraph = document.querySelector("p");
paragraph.style.overflow = "hidden";
paragraph.style.textIndent = "-1000%";
You could, alternatively, create a custom class meant to set overflow and text-indent, and toggle that class with JavaScript (jQuery?) instead:
paragraph.classList.toggle( "offsetChildren" );
// jQuery: $(paragraph).toggleClass( "offsetChildren" );
Fiddle: http://jsfiddle.net/6UZ82/
Try this code
function Hide(ptext,aText){
var p = document.getElementsByTagName('p');
var a = document.getElementsByTagName('a');
for(var i=0;i<a.length;i++){
if(a[i].innerHTML==aText){
a[i].setAttribute("style","display:none") ;
}
}
for(var i=0;i<p.length;i++){
var str = p[i].innerHTML;
var rp = str.replace(ptext,'<span style="display:none">'+ptext+'</span>');
p[i].innerHTML = rp;
}
}
Hide('some text','Link text here');
Also you can show back using the reverse logic. i have commented out the show function in fiddle. you can uncomment it and click run to see it in action
Demo here

How can I Strip all regular html tags except <a></a>, <img>(attributes inside) and <br> with javascript?

When a user create a message there is a multibox and this multibox is connected to a design panel which lets users change fonts, color, size etc.. When the message is submited the message will be displayed with html tags if the user have changed color, size etc on the font.
Note: I need the design panel, I know its possible to remove it but this is not the case :)
It's a Sharepoint standard, The only solution I have is to use javascript to strip these tags when it displayed. The user should only be able to insert links, images and add linebreaks.
Which means that all html tags should be stripped except <a></a>, <img> and <br> tags.
Its also important that the attributes inside the the <img> tag that wont be removed. It could be isplayed like this:
<img src="/image/Penguins.jpg" alt="Penguins.jpg" style="margin:5px;width:331px;">
How can I accomplish this with javascript?
I used to use this following codebehind C# code which worked perfectly but it would strip all html tags except <br> tag only.
public string Strip(string text)
{
return Regex.Replace(text, #"<(?!br[\x20/>])[^<>]+>", string.Empty);
}
Any kind of help is appreciated alot
Does this do what you want? http://jsfiddle.net/smerny/r7vhd/
$("body").find("*").not("a,img,br").each(function() {
$(this).replaceWith(this.innerHTML);
});
Basically select everything except a, img, br and replace them with their content.
Smerny's answer is working well except that the HTML structure is like:
var s = '<div><div>Link<span> Span</span><li></li></div></div>';
var $s = $(s);
$s.find("*").not("a,img,br").each(function() {
$(this).replaceWith(this.innerHTML);
});
console.log($s.html());
The live code is here: http://jsfiddle.net/btvuut55/1/
This happens when there are more than two wrapper outside (two divs in the example above).
Because jQuery reaches the most outside div first, and its innerHTML, which contains span has been retained.
This answer $('#container').find('*:not(br,a,img)').contents().unwrap() fails to deal with tags with empty content.
A working solution is simple: loop from the most inner element towards outside:
var $elements = $s.find("*").not("a,img,br");
for (var i = $elements.length - 1; i >= 0; i--) {
var e = $elements[i];
$(e).replaceWith(e.innerHTML);
}
The working copy is: http://jsfiddle.net/btvuut55/3/
with jQuery you can find all the elements you don't want - then use unwrap to strip the tags
$('#container').find('*:not(br,a,img)').contents().unwrap()
FIDDLE
I think it would be better to extract to good tags. It is easy to match a few tags than to remove the rest of the element and all html possibilities. Try something like this, I tested it and it works fine:
// the following regex matches the good tags with attrinutes an inner content
var ptt = new RegExp("<(?:img|a|br){1}.*/?>(?:(?:.|\n)*</(?:img|a|br){1}>)?", "g");
var input = "<this string would contain the html input to clean>";
var result = "";
var match = ptt.exec(input);
while (match) {
result += match;
match = ptt.exec(input);
}
// result will contain the clean HTML with only the good tags
console.log(result);

Insert an hidden character in text string using JavaScript

How to use an hidden character in text string using JavaScript.There is one text string which i read and writes back with the hidden character in it (so rewritten text looks same as the original text though it comtains the hidden character), so that next time i read the text i can come to know that this text is aleady read as it contains the hidden character
Eg)
< html>
< body>
< div>
This is a simple text
< /div>
< /body>
< /html>
I am trying to parse the div and extract the contents of the div, and insert an hidden character to the text and rewrite the text to the div again using JavaScript.
I just want to know which hidden character should i use to insert into the text ?
How to write the hidden character into the text ?
Since you are using javascript why don't you just add a property to the div:-
var divs = document.getElementByTagName("div");
for (var i = 0, length = divs.length; i < length; i++)
{
if (!divs[i].hasBeenRead)
{
fnReadDiv(divs[i]);
divs[i].hasBeenRead = true;
}
}
To answer the question, keep an array of the divs that have been traversed:
var divsChecked = [];
//code that looks at the div
divsChecked.push(div.getAttribute('id'));
However I think that the method that you are using to traverse the items may not be correct with libraries like jQuery you could loop over each div in turn thereby you shouldn't ever see the same div twice unless you run the loop twice.

Categories