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

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>

Related

Remove dollar sign from dom text - not from js code

I'm trying to replace all occurences of '$' (dollar sign) in a web page with another string.
The problem is that there may be some <script> tags that may contain the '$' (jQuery code) that I don't want to change.
For example:
document.body.innerHTML = document.body.innerHTML.replace(/\$/g, 'xxx'); seems to work, but also replaces '$' from any <script>$('...')...</script> parts.
Is this achievable?
Thank you in advance.
EDIT: I cannot modify the way the page is generated or change all other js parts - neither use some server-side logic. I can only add some custom js code
You can filter out the script tags
[].slice.call(document.body.children).forEach(function(element) {
if ( element.tagName.toLowerCase() != 'script' ) {
element.innerHTML = element.innerHTML.replace(/\$/g, 'xxx');
}
});
FIDDLE
This is not recursive, which means it only works for script tags directly under the body tag, not script tags that are nested deeper
function textNodes(main) {
var arr = [];
var loop = function(main) {
do {
if(main.hasChildNodes() && (["STYLE","SCRIPT"].indexOf(main.nodeName)==-1)){
loop(main.firstChild);
} else if(main.nodeType === 3) {
arr.push(main)
}
}
while (main = main.nextSibling);
}
loop(main);
return arr;
}
textNodes(document.body).forEach(function(a){a.textContent=a.textContent.replace(/\$/g,'€')});
Based on this DOM walking example

Get HTML without sub-children [duplicate]

This question already has answers here:
getting the first line of text in an element jquery
(5 answers)
Closed 8 years ago.
So, I have a piece of HTML code that looks something like this:
<span class="name">SOMEUSERNAME<span class="meta">20 friends</span></span>
With a simple $(".name") I can easily the insides, but is there a way to get just the username without the meta data? I know I could use RegEx, but I'd rather know if it can be done with jQuery selectors directly, since I'm still somewhat new to that thing.
Seems like something that would be easier without jQuery
document.querySelectorAll('.name')[0].firstChild.nodeValue
FIDDLE
for more elements you can do
var users = Array.prototype.slice.call(document.querySelectorAll('.name')).map(function(el) {
return el.firstChild.nodeValue;
});
FIDDLE
or for older browsers
var elems = document.querySelectorAll('.name');
users = [];
for (var i=elems.length; i--;) {
users.push(elems[i].firstChild.nodeValue);
}
FIDDLE
or more jQuery'ish
var users = $.map($('.name'), function(el) {
return el.firstChild.nodeValue;
});
FIDDLE
Try this:
var name = $('#name').clone();
name.find('.meta').remove();
console.log(name);
Hope this helps.
Try this, if you just want the username (without the 20 friends stuff)
$(".name").clone().children().remove().end().text();
http://jsfiddle.net/9GEfY/
.contents() will return all children, including text nodes. You can do something like this:
http://jsfiddle.net/MnCDb/
$(".name").contents().get(0).textContent;
Why don't you try like this?
<span class="name" id="name">SOMEUSERNAME
<span class="meta" id="meta">20 friends</span>
</span>
<button onClick="foo()">click me </button>
<div id='result'></div>
<script>
function foo(){
var names=document.getElementById('name').innerHtml;
document.getElementById('result').innerHtml=names;
}
</script>
$('span').filter(function(){return this.className=='name'}).get(0).firstChild;
jsFiddle example
Not sure this is the most efficient approach, but this should work:
$('.name').clone().children().remove().end().text();
Edit: here's a more efficient solution:
var text = $.map($('.name').contents(), function(node) {
return node.nodeType === 3 ? node.nodeValue : '';
}).join('');
Edit: just for fun, here's a potentially "more idiomatic" jQuery approach:
var text = $($('.name').contents()).filter(function() {
return this.nodeType === 3;
}).map(function() {
return this.nodeValue;
}).get().join('')

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)

jQuery javascript way of checking if some html exist on page

Before appending more code, I want to make sure:
<a href='index.php?option=com_content&view=article&id=36'>Hello</a>
isn't already on the html page inside the div where id='faqs'
<div id='faqs'>
<a href='index.php?option=com_content&view=article&id=36'>Hello</a>
</div>
What is the best way of doing this with jquery or javascript?
Thanks
The easiest way would be to use jQuery to select the element, and check the length property of the resulting object:
var anchor = $('#faqs a[href="index.php?option=com_content&view=article&id=36"]')
if(anchor.length == 0) {
// element isn't on the page
}
You could search using indexOf
var inBlock = $('#faqs').html();
if (inBlock.indexOf("<a href='index.php?option=com_content&view=article&id=36'>Hello</a>") == -1) {
$('#faqs').append ("<a href='index.php?option=com_content&view=article&id=36'>Hello</a>");
}
if (!$('a[href$="view=article&id=36"]', '#faqs').length) {
//does'nt exist
}
If the goal is to end up with the a tag as a child in the div tag, and thats it, then don't bother checking, just re add it, like this:
$('#faqs').html('');
$('<a />')
.attr('href', 'index.php?option=com_content&view=article&id=36')
.html('hello')
.appendTo($('#faqs'))​;​
However, if you genuinely need to check if it exists, then you can do something like this:
var exists = $('#faqs a[href="index.php?option=com_content&view=article&id=36"]').length > 0;
UPDATE
Finding the string in the html can be done as follows, but this is not a recommended solution. You may run into issues with different browsers encoding html in different ways etc (tested in chrome):
var stringToFind = 'Hello';
// need to replace the & ...
stringToFind = stringToFind.replace(/&/g, '&');
var exists = $('#faqs').html().indexOf(stringToFind) > -1;
if (exists) {
// do something
} else {
// do something else
}
Here's a working example -> http://jsfiddle.net/Uzef8/2/

Need Regexp for classname replace

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.

Categories

Resources