Remove style attributes from string - javascript

I'm trying to remove all style attributes from a string (and not an object), in JavaScript or jQuery.
Example
var html = "<p style="color:red">my text</p>";
And I want to obtain this:
<p>my text</p>
Is it possible to do it without calling the functions that we can call on objects (as removeAttr)?
Thanks

If you are not looking to use JavaScript or jQuery objects, have you tried using regular expressions?
This answer to a previous question shows a php version that can be adapted to JavaScript using the replace function.

See if this helps.
$("button").click(function() {
$("p").removeAttr("style");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p style="color:red">my text</p>
<button>Remove the style attribute from all p elements</button>

Related

jQuery 'HTML function doesn't work with special characters

I am trying to pass the string "{<A+_2OF3_MSF}" to jQuery's HTML function. It doesn't work because of special character <. I tried encoding/escaping an HTML tag using this escapeHtml function, but I am facing another issue after that.
var escapeHtml = function(theString) {
return theString.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
};
It appends HTML-encoded string as text, not as HTML. I saw the below Stack Overflow post, but then it suggests to decode it after encoding. If I do that I am back to square one.
Appending HTML-encoded string as HTML, not as text
I have created a fiddle:
https://jsfiddle.net/1aktfzm8/
You need to use .text() instead of .html()
$(document).ready(function(){
$("button").click(function(){
$("p").html("<span id=\"span\"> {A+_\"2OF3_MSF\"} </span>");
$('#span').text();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Change content of all p elements</button>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
This code is working normally: https://jsfiddle.net/kilotonna/eg4be1gr/1/
$(document).ready(function(){
$("button").click(function(){
$("p").html("{<A+_2OF3_MSF}".replace(/</g, '<'));
});
});

How does one add HTML code in a JS function?

I am using the following js to replace text in a class called .relatedactivities with another text. In the example below the text is Related Activities.
<script>
$(document).ready(function(){
$(".relatedactivities").text('Related Activities');
})
</script>
How can I replace the text "Related Activities" with the HTML code below instead?
<h1 class="GreenLrg" align="center">Related Activities</h1>
<div align="center"> <a href="/activities/kauai/ziplineadventures/koloa-zipline.htm">
<div class="CatBox"><img src="/Portals/0/1koloa-zipline-tour-2.jpg" height="174" width="231"><span>Koloa Zipline Tour</span></div>
</a> <a href="/activities/kauai/ziplineadventures/zip-n-dip-expedition.htm">
<div class="CatBox"><img src="/Portals/0/2zip-n-dip-2.jpg" height="174" width="231"><span>Zip N' Dip Expedition</span></div>
</a> <a href="/activities/kauai/ziplineadventures/kipu-falls-safari.htm">
<div class="CatBox"><img src="/Portals/0/3kipu-zipline-safari-2.jpg" height="174" width="231"><span>Kipu Zipline Safari</span></div>
<p></p>
</a></div><a href="/activities/kauai/ziplineadventures/kipu-falls-safari.htm">
I do not suggest you hard code HTML in your JavaScript, as it will become extremely difficult to maintain in the long run.
In a perfect world, you can call a backend service via AJAX which would return HTML, or you could use a framework or library like AngularJS or React.JS.
Now, to answer you question, simply change .text() for .html('<html here/>').
You'll need to use .html() instead of .text():
$(".relatedactivities").html('<h1 class="GreenLrg" align="center">Related Activities</h1>...');
Use: html() like
$(".relatedactivities").html('your code html');
This method uses the browser's innerHTML property. Some browsers may not return HTML that exactly replicates the HTML source in an original document. For example, Internet Explorer sometimes leaves off the quotes around attribute values if they contain only alphanumeric characters.
For more about that, check http://api.jquery.com/html/

jquery or native can't get element by its ID

So, in a page there is a div with id #SCPcustomOptionsDiv. I want to move that div to a right place where it should be.
I tried using jQuery as well as native javascript, but can't get this to work. When i try to run the script using debugger, the result is null. here is the script.
jQuery('#SCPCustomOptionsDiv') // return []
document.getElementById('SCPCustomOptionsDiv') // return null
and here is some snippet of the source
<span style="display:none;" class="scp-please-wait"><img src="http://optimallyorganic.webmate.co/skin/frontend/base/default/images/scp-ajax-loader.1413318518.gif" class="v-middle" alt="" /> Loading... </span>
<div id="SCPcustomOptionsDiv"></div>
</fieldset>
<script type="text/javascript">
$$('#product-options-wrapper dl').each(function(label) {
label.addClassName('last');
});
</script>
is camelcase id matter when selecting the div using javascript?
The C in SCPcustomOptionsDiv is lowercase in your HTML and uppercase in your script. IDs are case-sensitive.
SCPcustomOptionsDiv
^
vs.
SCPCustomOptionsDiv
^
Use SCPcustomOptionsDiv in your script not SCPCustomOptionsDiv
jQuery('#SCPcustomOptionsDiv')
document.getElementById('SCPcustomOptionsDiv')

Cannot get the hidden tag value

Here is my code:
<html>
<head>
<script type="text/javascript">
var x= document.getElementById("2").value;
document.getElementById("1").innerHtml = x;
</script>
</head>
<body>
<p hidden="hidden" id="2">This paragraph should be hidden.</p>
<p>This is a visible paragraph.</p>
<p><b>Note:</b> The hidden attribute is not supported in IE.</p>
<p id="1"></p>
</body>
</html>
in this code i have a hidden tag as you can see. I want that the javascript code read text value of the p tag with an id 2 and then print the same value to other <p> tag wiht id="1". But this is not working. Earlier i even tried to use nodeValue but also this is not working and when i checked out in google developer tool then it was showing an error as following:
Cannot read property 'value/nodeValue' of null
please note:
after a quick experiment i noted that after adding a event handler <body onload="y();>" there was no error but there was no expected result!
please help!
hidden is an input element type, not a p attribute:
<input type="hidden" id="2" value="This input should be hidden." />
There are three problems:
there is no innerHtml, innerHTML is the correct syntax.
the hidden "p" does not have a value, it is not an input field. use innerHTML for accessing it.
your javascript code runs before the browser knows about paragraps, so they don't exist when you want them to be accessed. put javascript after the paragraphs or run the code after the page is loaded.
this should work:
<html>
<head>
</head>
<body>
<p hidden="hidden" id="2">This paragraph should be hidden.</p>
<p>This is a visible paragraph.</p>
<p><b>Note:</b> The hidden attribute is not supported in IE.</p>
<p id="1"></p>
<script type="text/javascript">
var x= document.getElementById("2").innerHTML;
document.getElementById("1").innerHTML = x;
</script>
</body>
</html>
Don't use numbers for ID.
Try something like <p id="hello"></p>
I think you need to change your tag to then you can set a CSS class with .hidden { display:none; }.
Wrap your Javascript in a function and call it when you need to or go back to your
Also as Maaz said, try not to use numbers in your ID's.
var hiddenValue = document.getElementById('2').innerHTML;
document.getElementById('1').innerHTML = hiddenValue;
The problem with this (and if you try and style it also) is that classes and ID's should not start with (or include) numbers.
Rename your ID's to one and two and then update your javascript accordingly.
e.g
<p id="one">Some stuff</p>
Also hidden cannot be used with a p element as it's for inputs only.
You're better off using display:none; in CSS.
If you NEED to access it via css as a number, you can use
[id='1']{
/*code*/
}
but your javascript still wont work.
As James has pointed out, using numbers for ID's is perfectly valid in HTML5.

how to remove tags with JavaScript regular expressions

I have a JavaScript string containing HTML like this:
<div>
<div class="a">
content1
</div>
content 2
<div class="a">
<b>content 3</b>
</div>
</div>
and I want to remove the div's of class="a" but leave their content.
In Python I would use something like:
re.compile('<div class="a">(.*?)</div>', re.DOTALL).sub(r'\1', html)
What is the equivalent using Javascript regular expressions?
Why don't you use proper DOM methods? With a little help from jQuery, that's dead simple:
var contents = $('<div><div class="a">content1</div>content 2<div class="a"><b>content 3</b></div></div>');
contents.find('.a').each(function() {
$(this).replaceWith($(this).html());
});
You can achieve it with regular expressions in JavaScript
var html = '<div> <div class="a"> content1 </div> <div class="a"> content1 </div> ... </div>';
var result = html.replace(/<div class="a">(.*?)<\/div>/g, function(a,s){return s;});
alert(result);
RegExp method replace takes two parameters - first one is the actual re and the second one is the replacement. Since there is not one but unknown number of replacements then a function can be used.
If you want to do this in Javascript, I'm presuming that you are running it in a web browser, and that the 'javascript string' that you refer to was extracted from the DOM in some way.
If both of these case are true, then I'd say that it would be a good idea to use a tried and tested javascript library, such as JQuery (There are others out there, but I don't use them, so can't really comment)
JQuery allows you to do on-the-fly DOM manipulations like you describe, with relative ease...
$('div.a').each(function(){$(this).replaceWith($(this).html());});
JQuery is definitely one of those tools that pays dividends - a failry short learning curve and a whole lot of power.

Categories