Is the use of CDATA correct to replace < - javascript

Am I using the CDATA correctly in code below because I am getting no error but getting warnings on start tag < starting here...
var $tbody = $('#qandatbl_onthefly > tbody');
var $tr = $("<![CDATA[<tr class='optionAndAnswer' align='center'>]]");
var $qid = $("<![CDATA[<td width='5%' class='qid'></td>]]").text(qnum);
var $options = $("<![CDATA[<td><table class='option'><tbody><tr><td class='opt'>1. Option Type:</td></tr></tbody></table></td>]]");
var $video = $("<![CDATA[<td width='17%' class='video'></td>]]");
var $endtr = $("<![CDATA[</tr>]]");
var $questionType = '';

You probably don't need the CDATA sections, but the ones you have are incomplete. The end is missing an additional >:
<![CDATA[ ... ]]>
<![CDATA[ <div>...</div> ]]>
The trailing angle bracket is missing in the examples you provided.

I think you dont need to use CDATA here. It's used when you get data from XML to recognize that it is the HTML content

Related

Get class from <body> tag within HTML string

I have a string of HTML like this
var html = "<html><head></head><body class='getMe'></body></html>";
I want to get the body tags class and I tried doing that like this.
$(html).filter("body").attr("class")
$(html).find("body").attr("class");
But both methods return undefined. Any help?
You do not need to parse into html, rather try RegExp:
var html = "<html><head></head><body class='getMe'></body></html>";
var clazz = html.match(/body\sclass=['|"]([^'|"]*)['|"]/)[1]; //getMe
Here, String.match() gives array of string for given pattern.
body\sclass=['|"]([^'|"]*)['|"] gives ["body class='getMe'", "getMe"]. Using (), you can grab a particular group.
Also works with multiple classes and other attributes:
var html = "<html><head></head><body class='getMe hey there' id='xyz' bgcolor='red'></body></html>";
var clazz = html.match(/body\sclass=['|"]([^'|"]*)['|"]/)[1]; //getMe hey there
Edited
In order to get classes belonging to body tag starting with header-:
var html = "<html><head></head><body class='getMe header header-1 header-two test'></body></html>";
var headers = html.match(/body\sclass=['|"]([^'|"]*)['|"]/)[1].match(/(header\-\w+)/g);
//["header-1", "header-two"]
Try
var html = "<html><head></head><body class='getMe'></body></html>";
var className = $("<html />", {"html":html}).find("body")[0].className;
console.log(className);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
Did you try to put it in a Variable? find the tag without ""
var MyClass = $(body).attr("class");
// or $(html).find(body).attr("class");

Why is HTML elements is displayed as text?

I'm working on a form builder website. After a form is built it must be saved in database. When the user clicks on a form name from the list of saved forms the form information is restored from database. One of the variables I will restore is the structure of the form. In javascript I wrote these lines of code:
var prefix_content='<!DOCTYPE HTML>\n<html lang="en-US">\n<head>\n<meta charset="UTF-8">\n<title> </title>\n </head>\n<body>\n ';
var sufex_content=' \n</body></html>';
var dynamic_content=String(text_content);
document.write(prefix_content + dynamic_content + sufex_content );
The variable dynamic_content contains the dynamic structure.
The problem is that prefix_content and sufex_content is displayed as html but dynamic_content is written in the page as text. Any one knows why is that or knows how to solve this problem.
Note: when I write the text in dynamic content statically between single quotes it is displayed as html not text.
If you're seeing the content retrieved from your database as plaintext, instead of HTML, its HTML entities are probably getting escaped somewhere along the way. Check the contents of your text_content variable (e.g. use console.log(text_content) and if you're seeing stuff like <div> instead of <div>, go on and find out where your escaping happens and either remove it or manually unescape.
TRY THIS:
var prefix_content='<!DOCTYPE HTML>\n<html lang="en-US">\n<head>\n<meta charset="UTF-8">\n<title> </title>\n </head>\n<body>\n ';
var sufex_content=' \n</body></html>';
var dynamic_content=String(text_content);
var parser = new DOMParser();
var el = parser.parseFromString(dynamic_content, "text/html");
document.write(prefix_content + el + sufex_content );
Or you can try this too: Using jQuery
var dynamic_content=String(text_content);
var el = $.parseHTML( dynamic_content );
document.write(prefix_content + el + sufex_content );
var content = "<div style='color:red;'>TEST</div>";
var prefix ='<!DOCTYPE HTML>\n<html lang="en-US">\n<head>\n<meta charset="UTF-8">\n<title>TEST</title>\n</head>\n<body>\n';
var suffix ='\n</body></html>';
var all = prefix + content + suffix;
var parser = new DOMParser();
var doc = parser.parseFromString(all, "text/html");
console.log(doc.children[0].outerHTML);
Instead of children[0] you can also go for:
doc.documentElement.outerHTML
Results in:
<html lang="en-US"><head>
<meta charset="UTF-8">
<title>TEST</title>
</head>
<body>
<div style="color:red;">TEST</div>
</body></html>

Jquery .text() stripping html not working in IE-8

I have a javascript code :
<html>
<head>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function datacheck(content){
var content = "<script>for(var i = 0 ; i< 10 ; i++) alert('hello')</script>";
var text = $(content).text();
alert(text);
}
</script>
<body>
<div>
Click <input type="button" name="button1" onclick="datacheck()" />
</div>
</body>
</html>
$(content).text(); is working in all browsers striping out html content but not working in IE-8 , if I use
var content = "<p>for(var i = 0 ; i< 10 ; i++) alert('hello')</p>";
then it is working fine in IE-8 too.
Can anyone help me how can I make $(content).text(); working in IE8 too.
Every help is appreciated.
The problem is that the browser is seeing the <script> tags in the string and deciding that this means the end of the script.
Lesson 1: Never include a <script> tag inside your javascript code, even if it's within a string. There is a chance that browsers might mis-interpret it.
Ways around it:
Include comments or CDATA tags around your script code. eg
<script>
<!--
...... js code here ........
-->
</script>
Break the <script> tags in your string up into substrings. eg
var content = "<sc"+"ript>for(var i = 0 ; i< 10 ; i++) alert('hello')</scr"+"ipt>";
Just don't use <script> tags in this way -- if you're using it to inject JS code into your page, there are almost certainly better ways of doing so. Perhaps you should use a library like require.js?
You probably need a CDATA tag.
<script>
<![CDATA[
function datacheck(content){
var content = "<script>for(var i = 0 ; i< 10 ; i++) alert('hello')</script>";
var text = $(content).text();
alert(text);
}
]]>
</script>
<script>
function datacheck(content){
var content = "<script>for(var i = 0 ; i< 10 ; i++) alert('hello')</script>";
content = '<![CDATA[' + content + ']]>';
var text = ($(content).text()).replace(']]>', '');
alert(text);
}
</script>
This will work correctly.
Thanks tea2code for your answer.

Accessing inline CSS properties using getElementsByClassName

I have this piece of HTML code.
<div class="tagWrapper">
<i style="background-image: url(https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/390945_10150419199065735_543370734_8636909_2105028019_a.jpg);"></i>
</div>
I need to get that url within the brackets. I tried using the getElementsByClassName() method but it didn't work. Since url is not a HTML element, I have no idea on how to take out the value. I can't use getElementById(), because I can't add an id to the HTML (it's not mine). It needs to work in Chrome and Firefox. Any suggestions?
You didn't add a jQuery tag, so here's a native solution (note that this likely won't work on older versions of IE, but you said it only has to work on Chrome and FF):
var origUrl = document.getElementsByClassName("tagWrapper")[0]
.children[0].style.backgroundImage;
var url = origUrl.substr(4, origUrl.length - 5);
Or
var url = origUrl.replace("url(", "").replace(")", "");
Here's a fiddle
EDIT
Answering your comment
document.getElementsByClassName("tagWrapper")
gets all elements with the class name tagWrapper. So to get the first one, you grab the zero index
document.getElementsByClassName("tagWrapper")[0]
Then you want the first child under there, and the backgroundImage property on this first child.
document.getElementsByClassName("tagWrapper")[0]
.children[0].style.backgroundImage;
From there it's a simple matter stripping the url( and ) from it
var url = origUrl.substr(4, origUrl.length - 5);
or
var url = origUrl.replace("url(", "").replace(")", "");
You can use querySelector():
Demo: http://jsfiddle.net/ThinkingStiff/gFy6R/
Script:
var url = document.querySelector( '.tagWrapper i' ).style.backgroundImage;
url = url.substr(4, url.length - 5);
If you where using jquery you could do something like this
$(".tagWrapper i").css("background-image")
I think if you use jQuery it will be easer.
var w = document.getElementsByClassName('tagWrapper')[0];
for (var i=0; i<w.childNodes.length; i++)
if (w.childNodes[i].tagName && w.childNodes[i].tagName.toLowerCase() == 'i')
return w.childNodes[i].style.backgroundImage;
<div class="tagWrapper">
<i id="something" style="background-image: url(https://fbcdn-photos-a.akamaihd.net/hphotos-ak-ash4/390945_10150419199065735_543370734_8636909_2105028019_a.jpg);"></i>
</div>
// script / without jQuery
var url = document.getElementById('something').style.backgroundImage.match(/\((.*?)\)/)[1];
Use jQuery!!!
$("div.tagWrapper i").css("background-image").substr(4, $("div.tagWrapper i").css("background-image").length-5)
Example
If You don't have to care about Microsoft browsers, the raw JavaScript is quite easy. You can use getElementsByClassName and getElementsByTagName, however it is easier to try querySelectorAll. I've included both. The use of regular expression preserve relative links.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type='text/javascript'>
var do_find_a = function() {
var tmp = document.getElementsByClassName('tagWrapper')[0];
var tst = tmp.getElementsByTagName('i')[0].getAttribute('style');
return do_alert(tst);
}
var do_find_b = function() {
var tst = document.querySelectorAll('.tagWrapper i')[0].getAttribute('style');
return do_alert(tst);
}
var do_alert = function(tst) {
var reg = /background-image:\s*url\(["']?([^'"]*)["']?\);?/
var ret = reg.exec(tst);
alert (ret[1]);
return;
}
document.addEventListener('DOMContentLoaded',do_find_a,false);
document.addEventListener('DOMContentLoaded',do_find_b,false);
</script>
</head>
<body>
<div class='tagWrapper'>
<i style='background-image: url("http://example.com/image.jpg");'></i>
</div>
Text to ignore.
</body>
</html>
And jsFiddle version:
http://jsfiddle.net/hpgmr/

Javascript: Getting values from XML file

This is my exact xml file:
<?xml version="1.0" ?>
<blah_de_blah>
<unblocker_details table_color="#F2F0FF" type="zip" alt_link="http://g.org/288"
link_for_deletion="3-QQ5DJoa-AWFT7a9" comment="zippy" />
<unblocker_details table_color="#FFFFFF" type="Webpage" alt_link="http://www.gg.com"
link_for_deletion="4-rOX2brr-2qQeGY3" comment="test" />
</blah_de_blah>
I have successfully gotten it via an ajax request, then did this:
var xmlDoc=null;
var parser = new DOMParser();
xmlDoc = parser.parseFromString(data, "text/xml");
and now I need to get each of those values from unblocker_details into a variable:
for example:
the_table_color=table_color;
the_type =type;
etc
Please also check if I declared the xml properly as I am very new to this.
Thanks!
Something like this:
var nodes = xmlDoc.getElementsByTagName("unblocker_details");
for(i=0; i< nodes.length; i++) {
the_table_color = nodes[i].getAttribute("table_color");
// get other attributes the same way
}
You can use this http://www.w3schools.com/ajax/ajax_xmlfile.asp

Categories

Resources