Replace STYLE content javascript HTML - javascript

I have a JavaScript variable:
var s =
"<html><head><style>body{a:b;c:d}</style></head><body></body></html>";
First, I am extracting the content inside <style> tags:
s = s.split(/(<style[^>]*>|<\/style>)/i)[2];
// s == "body{a:b;c:d}";
Then I am doing something with s and after the manipulation I need to append it on <style> tags.
How can I insert s between <style> and </style> ?
Example: Modified var s = "body{x:h;f:l;}";
so I need the resulting content like this:
"<html><head><style>body{x:h;f:l;}</style></head><body></body></html>";
Update: jQuery is allowed - But only string manipulation is
allowed. Pure JavaScript solutions have first priority.

var s = "<html><head><style>body{a:b;c:d}</style></head><body></body></html>";
var b = s.split(/(<style[^>]*>|<\/style>)/i)[2];
s = s.replace(b,"body{x:h;f:l;}");
finally, s is what you want.

Does this work for you:
var s ="body{a:b;c:d}";
var newS = s.replace("body{a:b;c:d}", "body{x:h;f:l;}");
alert(s);
alert(newS);

Use below mentioned code
var someHTML = "<html><head><style>body{a:b;c:d}</style></head><body></body></html>";
var styleContents = someHTML.split(/(<style[^>]*>|<\/style>)/i)[2];
document.getElementById('style').innerHTML = styleContents;

Related

How to extract all html text excluding what's inside the script tag?

For a project I want to create a variable that stores all the text within the html, so pretty much everything between tags, titles, paragraphs, everything visible for a user on a webpage. However I don't want my javascript code that's between the script tag to show up in this output too.
I was trying with something like this:
var content = $("html").remove("script").text()
But this is not working.
Here it is:
First use this:
var r = document.getElementsByTagName('script');
for (var i = (r.length-1); i >= 0; i--) {
if(r[i].getAttribute('id') != 'a'){
r[i].parentNode.removeChild(r[i]);
}
}
And then:
var txt = document.body.innerText;
OR
var txt = $('body').text();
var contentDiv = $('<div/>', {
html: $('body').clone()
});
contentDiv.find('script').remove()
return contentDiv.text()

How to create a DOM element from a template?

Suppose I have a template saved in HTML and using standard underscore syntax.
My understanding is that I can grab the template using jQuery as such:
var html = $('#item-foo').html()
From there I can interpolate it using
var interpolated = _.template(html, {prop: "and_values"});
To create a DOM element in the JavaScript I can use this utility function
// converts HTML string to DOM object
Pub.HTMLToElement = function (html) {
var div = document.createElement('div');
div.innerHTML = html;
return div.firstChild;
};
var element = HTMLToElement(interpolated);
and finally I have my element in JavaScript which all began with a template in the HTML.
Is this the best way to do this?
It seemed long so I just wanted to validate.
This is a little bit simpler and you are already using jQuery:
HTML:
<script id="template" type="text/template">
Hello <%=name%>, how are you?
</script>
<div id="container" />
JS:
var str=$('#template').html();
var interpolated = _.template(str, {name: "pizza"});
$('#container').append($('<div/>').html(interpolated));
JSFiddle: http://jsfiddle.net/QAT4n/
If you are using jQuery, jQuery automatically converts HTML to an element. This would be a shorter way:
var element = $(interpolated).get(0);
See http://api.jquery.com/get/ and http://api.jquery.com/jQuery/#jQuery2
So the whole process would be like this:
var html = $('#item-foo').html()
var interpolated = _.template(html, {prop: "and_values"});
var element = $(interpolated).get(0);
And could be cleaned up to this:
var interpolated = _.template(
$('#item-foo').html()
, {
prop: "and_values"
});
var element = $(interpolated).get(0);

remove " " from script [duplicate]

I have written the following code. But it is removing only not <br>
var docDesc = docDescription.replace(/( )*/g,"");
var docDesc1 = docDescription.replace(/(<br>)*/g,"");
You can achieve removing <br> with CSS alone:
#some_element br {
display: none;
}
If that doesn't fit your needs, and you want to really delete each <br>, it depends, if docDescription is really a string (then one of the above solutions should work, notably Matt Blaine's) or a DOM node. In the latter case, you have to loop through the br elements:
//jquery method:
$('br').remove();
// plain JS:
var brs = common_parent_element.getElementsByTagName('br');
while (brs.length) {
brs[0].parentNode.removeChild(brs[0]);
}
Edit: Why Matt Baline's suggestion? Because he also handles the case, where the <br> appears in an XHTML context with closing slash. However, more complete would be this:
/<br[^>]*>/
Try:
var docDesc = docDescription.replace(/[&]nbsp[;]/gi," "); // removes all occurrences of
docDesc = docDesc.replace(/[<]br[^>]*[>]/gi,""); // removes all <br>
Try this
var text = docDescription.replace(/(?: |<br>)/g,'');
Try "\n"...see if it works.
What about:
var docDesc1 = docDescription.replace(/(<br ?\/?>)*/g,"");
This will depend on the input text but I've just checked that this works:
var result = 'foo <br> bar'.replace(/(<br>)*/g, '');
alert(result);
You can do it like this:
var cell = document.getElementsByTagName('br');
var length = cell.length;
for(var i = 0; i < length; i++) {
cell[0].parentNode.removeChild(cell[0]);
}
It works like a charm. No need for jQuery.
I using simple replace to remove and br tag.
JavaScript
var str = docDescription.replace(/ /g, '').replace(/\<br\s*[\/]?>/gi, '');
jQuery
Remove br with remove() or replaceWith()
$('br').remove();
or
$('br').replaceWith(function() {
return '';
});

Parse a string in jquery, change something and get the modified string back

I have a string containing html code, something like this: http://jsbin.com/ocoteg/1.
I want to parse this string, make some changes (just for example: change all links to a span), and then get the modified html string back.
Here is a jsbin, where I started this, but I can't make it work: http://jsbin.com/okireb/1/edit.
I get the html string, I parse it with jquery, but I can't replace the links, and get the modified html string back.
UPDATE
Why the downvote? What is the problem with this question?
You can do it in a loop also
dom.each(function(i,v){
if(v.tagName == "A"){
dom[i] = $('<span/>').html($(v).html())[0]; // replace it right away with new span element
}
});
var newString = $('<div>').append(dom.clone()).html(); //<-- to get new string http://stackoverflow.com/a/652771/1385672
console.log(newString);​
EDIT:
Here's how you can do it keeping the other tags
var dom = $(text.split('\n'));
$(dom).each(function(i,v){
var ele = $(v)[0];
if($(ele).is('a')){
dom[i] = $('<div>').append($('<span/>').html($(v).html())).html();
}
});
var newString = dom.get().join('\n');
http://jsbin.com/okireb/32/edit
Use find instead of filter :
var dom = $('<div>'+text+'</div>');
dom.find('a').each(function() {
var el = $(this);
var html = el.html();
var span = $('<span/>').html(html);
el.replaceWith(span);
});
console.log(dom.children()); ​
Note that I wrap everything for the case where the initial dom isn't one element.
Demonstration
To get the html back as a string use
var html = dom.html();
This should be what you want (can be improved)
var text = '<!DOCTYPE html><html><head><meta charset=utf-8 /><title>JS Bin</title></head><body>Link 1Link 2Link 3</body></html>';
var body_content = text.substring(text.indexOf('<body>') + 6, text.indexOf('</body>'));
var $dom = $('<div/>').html(body_content);
$('a', $dom).each(function() {
$('<span>' + $(this).html() + '</span>').insertAfter($(this));
$(this).remove();
});
var text_new = text.replace(body_content, $dom.html());
// text_new contains the entire HTML document with the links changed into spans
You could do it with .replace.
Probably not the nicest way of doing it though.
dom = dom.replace(/<a /g,'<span');
dom = dom.replace(/<\/a>/g,'</span>');
Demo: http://jsbin.com/okireb/14/edit

jQuery get attributes and values of element

Say I have this HTML code:
<img id="idgoeshere" src="srcgoeshere" otherproperty="value" />
I can reference the element by its id: $('#idgoeshere')) Now, I want to get all the properties and their values on that element:
src=srcgoeshere
otherproperty=value
Is there some way I can do that programmatically using jQuery and/or plain Javascript?
You can get a listing by inspecting the attributes property:
var attributes = document.getElementById('idgoeshere').attributes;
// OR
var attributes = $('#idgoeshere')[0].attributes;
alert(attributes[0].name);
alert(attributes[0].value);
$(attributes).each(function()
{
// Loop over each attribute
});
The syntax is
$('idgoeshere').attr('otherproperty')
For more information - http://api.jquery.com/attr/
Yes you can!
Jquery:
var src = $('#idgoeshere').attr('src');
var otherproperty = $('#idgoeshere').attr('otherproperty');
Javascript:
var src = document.getElementById('idgoeshere').getAttribute('src');
var otherproperty = document.getElementById('idgoeshere').getAttribute('otherproperty');
You can use attr for that:
For eg.
var mySrc = $('#idgoeshere').attr("src");
var otherProp = $('#idgoeshere').attr("otherproperty");
If you want to just get a list of all the attributes, see the answers to this question: Get all Attributes from a HTML element with Javascript/jQuery
Try this:
var element = $("#idgoeshere");
$(element[0].attributes).each(function() {
console.log(this.nodeName+':'+this.nodeValue);});

Categories