translate javascript/jquery to vba - javascript

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?

Related

Userscript to remove Html-Lines, class and Attributes

I want to create one short userscript because I hate this annoying yellow smileys!
There are two html lines witch turns the normal smiley ( :) ) into the yellow icon
<span class="emoticon_text" aria-hidden="true"> :) </span>
<span title=":)" class="emoticon emoticon_smile"></span>
So, in the first line I have to remove the class and the aria-hidden
And in the second the whole line, it can be class="emoticon emoticon_smile", but also something like class="emoticon emoticon_cool"
I tried with:
document.getElementsByClassName("emoticon_ text").removeAttribute("aria-hidden"); document.getElementsByClassName("emoticon_ text").className = "";
but it failed, so I hope you guys can help me, because my Javescript/jQuery skills are bad..
Thank you
sorry for my grammar mistakes
document.getElementsByClassName returns a HTMLCollection, which is basically a array of elements matched. You have to iterate trough that collection and run your code for each of the elements matched.
Secondly, you'll need to find the emoticon itself and remove it, for that you need to get each emoticon's parent and tell it to remove the element. In the end, your code will look similar to this:
//Finds all emoticon texts
var emoticonTexts = document.getElementsByClassName("emoticon_text");
//Iterate over the results and remove the desired attributes
for (var i = emoticonTexts.length-1; i >= 0; i -= 1) {
var element = emoticonTexts[i];
element.removeAttribute("aria-hidden");
element.className = "";
}
//Find all emoticon images
var emoticons = document.getElementsByClassName("emoticon");
//Iterate over the results and remove them from the page
for (var i = emoticons.length-1; i >= 0; i -= 1) {
var element = emoticons[i];
element.parentNode.removeChild(element);
}
Also available as an example on JSFiddle
I would look into using jQuery. Once you have the jQuery library referenced in your project your solution should be as simple as:
$(".emoticon_text").removeAttr("aria-hidden").removeClass("emoticon_text");

jquery & doc.createElement throws error for <

Both the $("<test") & document.createElement(",test") throws error due to < character associated to the text. I do not want to replace the character & wanted to see if there is option to create dom or jquery object using such text. I know replace will work but since the code is pre-existing & also since code is written such that it assume it can either have the simple text (textnode) or html tag (like span) hence this error is occuring as it fails to check if it is proper self closing html tag.
I am thinking of creating it to xml node & then check if the childnode is textNode or not before trying to create jquery object,however I am looking for suggestion & best approach to tackle such issue. I know replace of < will work & also there is no need to check for attributes of plain text but since the code is dynamic it sometimes retrieves plain text & some time it gives valid html tag that why this issue appears
I am not sure what your exact end goal is, but basically you need to do something like this:
function makeElemHack( str ) {
var div = $("<div>").html(str); //create a div and add the html
var html = div.html(); //read the html
if (!html.length) { //if the html has no length the str was invalid
div.html(str.replace(/</g,"<")); //escape the < like text should be
//div.text(str); //or you can just add it as plain text
}
return div; //with the div wraper
//return div.contents(); //without the div wrapper
}
var bd = $("body");
bd.append( makeElemHack("<p>Hello</p>") );
bd.append( makeElemHack("1<0") );
bd.append( makeElemHack("<booo") );

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.

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

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"

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);

Categories