Need Regexp for classname replace - javascript

I have following HTML code:
Its look like
<html>
<head>
</head>
<style id="styletag">
.class3{
}
.sec2{
}
.this3{
}
</style>
<body>
<div class="class1 class2 class3">content</div>
<div class="sec1 sec2 sec3">content2</div>
<div class="this1 this2 this3">content2</div>
</body>
</html>
I am having the values class3, sec2 and this3 in array.
I want to replace this class3,sec2 and this3 from the HTML code.
And I also want to remove the style tag entirely (its having the id name 'styletag').
How do i use the regexp?

Sorry if I misunderstood what you ask for.
for(var index=0; index<document.getElementsTagName("div").length; index++) {
if( document.getElementsTagName("div")[index].style.className.indexOf("class3")
|| document.getElementsTagName("div")[index].style.className.indexOf("sec2")
|| document.getElementsTagName("div")[index].style.className.indexOf("this3")
)
// assign a new css
document.getElementsTagName("div")[index].style.className = 'newCss';
// or clear style
// document.getElementsTagName("div")[index].style.className = '';
// or add up another style
// document.getElementsTagName("div")[index].style.className += ' newCSS';
}
And regarding removal of Style tag:
document.getElementById("styletag").parentNode.removeChild(document.getElementById("styletag"));

Forget regex. You can't use regex to parse HTML in any way reliably. And if you're running from JavaScript regex means reading and writing the entire document's innerHTML, which you should avoid.
Here's a JS version that's a bit more rigorous about detecting full and not just partial class names:
function Element_setClass(element, classname, active) {
var classes= element.className.split(' ');
var ix= classes.indexOf(classname);
if ((ix!==-1)===active)
return;
if (active)
classes.push(classname);
else
classes.splice(ix, 1);
element.className= classes.join(' ');
}
var els= document.getElentsByTagName('div');
for (var i= els.length; i-->0;) {
Element_setClass(els[i], 'class3', false);
Element_setClass(els[i], 'sec2', false);
Element_setClass(els[i], 'this3', false);
}
var el= document.getElementById('styletag');
el.parentNode.removeChild(el);
And though I'm loathe to drag in frameworks to a plain JavaScript question, I have to admit jQuery makes this very easy to spell:
$('.class3').removeClass('class3');
$('.sec2').removeClass('sec2');
$('.this3').removeClass('this3');
$('#styletag').remove();

Removing the classes works by replacing this:
(<div[^>]+class="[^"]*)\b(class3|this3|sec2)\b([^"]*")
with this:
$1$3
The style tag can be removed by replacing the following with a blank string:
<style id="styleTag">[^<]*<\/style>
Another good way to achieve the same would be using jQuery.

Related

How to replace < and > with < and > with jQuery or JS

I've been searching for a day or so how to do something with JS or jQuery and found a couple of solutions but nothing solid yet.
I want to use this:
<code class="codeIt">
<h2> This is an H2 </h2>
</code>
And I want the output to be:
<h2> This is an H2 </h2>
I know I can achieve this by doing:
<code class="codeIt">
<h2> This is an H2 </h2>
</code>
...But I would like to not do a manual search and replace on my code in those blocks and rather have it done on the fly in the browser. Is this possible?
I'm pretty noob with jQuery so I've tried .replaceWith or JavaScript's .replace but so far I've not gotten where I need to be with it. I'm either replacing the whole tag or doing something else wrong.
My question is: How would I write a simple jQuery (or regular JS) to help me replace my < and my > with HTML entities like < and > inside my <code> tags.
I appreciate any help, Thanks.
UPDATE:
I managed to get it working nice how #Prisoner explained, it's very nifty, however this in my particular case needed a little extending because I have more than one block of code with the .codeIt class, so I had to make it check each element and output... otherwise it would keep making the same output (like the first block)
Here is the fiddle
Thanks to everyone for their answers.
Assuming you just want to escape all HTML:
$(".codeIt").text($(".codeIt").html());
Plain JS for single code element
var myCode = document.getElementById('mycode');
myCode.innerHTML = myCode.innerHTML.replace(/</g,'<').replace(/>/g,'>')
Plain JS for multiple code elements
var codeEls = document.getElementsByTagName('code');
for(var i in codeEls)
{
if(parseInt(i)==i)
{
var codeEl = codeEls[i];
if(codeEl.className.match(/\bcodeIt\b/)!==null) codeEl.innerHTML = codeEl.innerHTML.replace(/</g,'<').replace(/>/g,'>')
}
}
or jQuery
$(".codeIt").each(function() {
$(this).html(
$(this).html().replace(/</g,'<').replace(/>/g,'>')
);
});
You could use the text function of jquery:
var myText = $('.codeIt').html();
var escapedText = $('.codeIt').text(myText).html();
var t = $('.codeIt').html();
$('.codeIt').text(t).html();
Look at this fiddle http://jsfiddle.net/kU8bV/1/
$('code').html($('code').html().replace(/</g, '<').replace(/>/g, '>'));
Assuming you want to code all the html in codeIt class :
<script type="text/javascript">
function htmlEncode(value){
if (value) {
return jQuery('<div />').text(value).html();
} else {
return '';
}
}
function htmlDecode(value) {
if (value) {
return $('<div />').html(value).text();
} else {
return '';
}
}
$('.codeIt').each(function() {
myEncodedString = htmlEncode($(this).html());
$(this).html(myEncodedString);
});
</script>

How to remove a Tag using javascript?

I'm in a bit of a pickle. What I'm trying to achieve is to remove a div IF it is empty and then do what I have to afterwards which is the easy bit. The hard part is trying to remove the empty tags. I'm using DNN and it likes to put in empty tags like p and br. I want to be able to remove them before performing my check. Here is my code so far
$(document).ready(function(){
var element = document.getElementsByTagName("p"); //Need to remove all tags. not just P
element.parentNode.removeChild(element); //Doesn't target which child
if( !$.trim( $('#container2Test').html() ).length ) {
alert("empty");
$('#container2Test').remove();
$('#container3Test').css({'width' : '50%', 'background-color' : '#3F0'});
$('#container3Test').append("This is some content");
}
else{
alert("not empty");
}
});
The html:
<div id="container1Test" style="width:30%; height:10em; background-color:#000;">
</div>
<div id="container2Test" style="width:50%; height:10em; background-color:#666;">
<p></p><br /><p></p>
</div>
<div id="container3Test" style="width:20%; height:10em; background-color:#F66;">
</div>
I've tried many options to try and remove the tags but I've had no such luck :( Please help!
As far as your container2test block goes, try using .text() instead of .html(). This will ignore the empty tags that get inserted and focus only on the text content.
Regarding the piece above it, I'm not quite sure what you're trying to achieve. I don't think it's needed if you implement the change I mentioned earlier.
I think this will be the solution you'll need... Check out that:
var elmsToClear = $('#container1Test, #container2Test, #container3Test');
elmsToClear.each(function(){
while($(this).find('*:empty').remove().length); // recursivly kill all empty elements
if(!$(this).find('*').length){ // if no elements left - kill the parent
alert($(this).attr('id') + ' is empty...');
$(this).remove();
}
else{ // there is something in here...
alert($(this).attr('id') + ' is NOT empty...');
}
});
>>> The JS-Fiddle of the Problem with Solution <<<
Greetings ;)
Notice that getElementsByTagName is plural:
var elements = document.getElementsByTagName("p");
for (var n=0; n < elements.length; n++) {
var element = elements[n];
element.parentNode.removeChild(element); // should work now
}
There is a removeChild() function. So why can't you do something like this:
$('div').each(function(){
if(this.innerHTML == ''){
this.parentNode.removechild(this);
}
});
(Haven't tested this)

How can access bunch of <li>?

I have a list of texts and I want to change their innerHTML. how can I do that by javascript if I have thousands of li tag (whose data come from database)?
<div>
<ul>
<li>a</li>
<li>as</li>
<li>asd</li>
<li>asds</li>
<li>asdsa</li>
<li>asdsad</li>
<li>asdsadz</li>
<li>asdsadzc</li>
....
.....
</ul>
</div>
-Thanks.
Update
JS code being used:
function a(){
var parent = document.getElementById("z");
var i = 0;
for(i = 0; i <= parent.children.length; i++){
if(parent.children[i].tagName == "LI"){
if(i%2!=0){
parent.children[i].innerHTML="ok";
}
}
}
}
document.onload=a(); // this didn't work. so I called the function in body tag instead of that.
<body onload="a();">
Have you tried using getElementsByTagName ? Sonds like it would help you find the elements you're trying to work with.
Edit
If you can give an Id to the UL element that holds the li's you're trying to process, you could do something like this:
var parent = document.getElementById("yourID");
var i = 0;
for(i = 0; i < parent.children.length; i++){
if(parent.children[i].tagName == "LI") {
//do what you want...
}
}
EDit 2
You have to change the last line on your script:
document.onload=a();
With this one: window.onload=a;
That'll get your function to execute on the onLoad event. Note that there might be some crossbrowser incompatibility, I would suggest researching a bit on how to execute functions on the onload event on a crossbrowser manner, or just adding this to your body tag:
<body onload="a();">
Given the - not so far fetched - precondition you wish to use jQuery, you can select them and iterate over them with "each".
$("li").each(
function() { $(this).html("changed content"); }
);
If you are not using jQuery, using a js-library that helps you out with the quircky dom is probably not a bad idea...
The general idea
Select nodes
Iterate and change html
is always the same.

Javascript DOM howto?

I am a javascript noob.
I would like to select the second 'p' element of the div.box.
How do I do this?
Thanks a lot!
Tom
To get second p element of div with class box you'd do this:
var paragraph = null;
var divs = document.findElementsByTagName('div');
for (var i = 0; i < divs.length; i++) {
var div = divs[i];
if (div.class == 'box') {
var paragraphs = div.getElementsByTagName('p');
if (paragraphs.length > 1)
paragraph = paragraphs[1];
break;
}
}
The paragraph would then be in the paragraph variable (or null if it wasn't found).
However you can do this much easier with a library such as jQuery:
var paragraph = $('div.box p:eq(1)');
Without using jQuery, the basic method would be to attach an unique ID to your Dom element
<p id="second_p_elmt"> [...] </p>
and then accessing it through the getElementById() method:
<script ...>
var second_p_elmt = document.getElementById('second_p_elmt');
</script>
<script type="text/javascript">
var boxElem = document.getElementById('box'),
pElems = boxElem.getElementsByTagName('p'),
whatYouWant = pElems[1]; // [1] is the second element in the response from getElementsByTagName
</script>
You have several options. As stated above, you could use one of the excellent frameworks, like jQuery or prototype. Or you give the <p/> an ID, that you can use simply with document.getElementById().
Then, as reko_t pointed out, without the above, you must write a lengthy DOM traversing code (which is preferable, if you don't use JS frameworks elsewhere, over embedding them only for this task).
In the most recent browsers (namely, IE>=8, FF>=3.5, recent Opera and Safari > 3) you can also use this simple snippet:
var p = document.querySelectorAll("div.box p");

Trying to replace html tags using regex

For the example, I'm trying to replace
<script type='text/javascript'>some stuff</script>
with:
<div type='text/javascript'>some stuff</div>
I'm currently testing with:
alert( o.replace( /(?:<\s*\/?\s*)(script)(?:\s*([^>]*)?\s*>)/gi ,'div') );
But what I'm getting is:
divsomestuffdiv
How can I get this to only replace the "script" portion and preserve the other markup and attribute characters?
You have keep the opening and closing tag brackets. So try this:
o.replace(/(<\s*\/?\s*)script(\s*([^>]*)?\s*>)/gi ,'$1div$2')
A naive but readable way would be to do it in two passes i suppose and first match and replace the
<script
part with
<div
and then another which would match
</script>
and replace it with
</div>
DOM methods are better suited for this than regular expressions. This way you'll manipulate your document logically instead of as plaintext:
var els = document.getElementsByTagName('script');
for (var i = 0, el; el = els[i]; i++) {
var new = document.createElement('div');
new.type = el.type;
el.parentNode.replaceChild(el, new);
}

Categories

Resources