Is there anyway to create a string and add to the DOM? And having Javascript to understand the elements in the string?
I tried the below and 4th line gives error:
var bmdiv = document.createElement('div');
bmdiv.setAttribute('id', 'myDiv');
var str = "<b>aa</b>";
bmdiv.innerHTML(str);
I need to add several tags in str to the DIV myDiv
I need NOT to use jQuery since the script will not load jQuery
Thanks.
The innerHTML property is not a function, you should assign it like this:
var bmdiv = document.createElement('div');
bmdiv.setAttribute('id', 'myDiv');
var str = "<b>aa</b>";
bmdiv.innerHTML = str;
Try
bmdiv.innerHTML = str;
Another way to do this is to manually create the DOM structure for each of the tags, then append them into the div.
Related
I have a string containing html elements, now I need to select some elements and remove them from the string.
In JQuery I tried the following:
html_string = "<ul><li data-delete>A<li><li>B</li></ul>";
html_clean_string = $(html_string).remove('[data-delete]').html();
This is what I expected:
"<ul><li>B</li></ul>"
But I got the same original string. So how can I use CSS selectors to remove html elements from a string?
You can do it like this:
var html_string = "<ul><li data-delete>A</li><li>B</li></ul>";
var elems = $(html_string);
elems.find('[data-delete]').remove();
var html_clean_string = elems[0].outerHTML;
You had a couple of issues:
.remove() only operates on the elements in the jQuery object, not on child object so you have to .find() the appropriate child elements before you can remove them.
Since you want the host top level HTML too, you will need the .outerHTML.
You had mistakes in your html_string.
Working jsFiddle: http://jsfiddle.net/jfriend00/x8ra6efz/
You can also save a little jQuery with more chaining like this:
var html_string = "<ul><li data-delete>A</li><li>B</li></ul>";
var html_clean_string = $(html_string).find('[data-delete]').remove().end()[0].outerHTML;
Working jsFiddle:http://jsfiddle.net/jfriend00/wmtascxf/
Let's say I have the following string:
var myString = "<p>hello</p><script>console.log('hello')</script><h1>Test</h1><script>console.log('world')</script>"
I would like to use split to get an array with the contents of the script tags. e.g. I want my output to be:
["console.log('hello')", "console.log('world')"]
I tried doing myString.split(/[<script></script>]/) But did not get the expected output.
Any help is appreciated.
You can't parse (X)HTML with regex.
Instead, you can parse it using innerHTML.
var element = document.createElement('div');
element.innerHTML = myString; // Parse HTML properly (but unsafely)
However, this is not safe. Even if innerHTML doesn't run the JS inside script elements, malicious strings can still run arbitrary JS, e.g. with <img src="//" onerror="alert()">.
To avoid that problem, you can use DOMImplementation.createHTMLDocument to create a new document, which can be used as a sandbox.
var doc = document.implementation.createHTMLDocument(); // Sandbox
doc.body.innerHTML = myString; // Parse HTML properly
Alternatively, new browsers support DOMParser:
var doc = new DOMParser().parseFromString(myString, 'text/html');
Once the HTML string has been parsed to the DOM, you can use DOM methods like getElementsByTagName or querySelectorAll to get all the script elements.
var scriptElements = doc.getElementsByTagName('script');
Finally, [].map can be used to obtain an array with the textContent of each script element.
var arrayScriptContents = [].map.call(scriptElements, function(el) {
return el.textContent;
});
The full code would be
var doc = document.implementation.createHTMLDocument(); // Sandbox
doc.body.innerHTML = myString; // Parse HTML properly
[].map.call(doc.getElementsByTagName('script'), function(el) {
return el.textContent;
});
Javascript Code:
function myFunction() {
var str = "<p>hello</p><script>console.log('hello')</script><h1>Test</h1><script>console.log('world')</script>";
console.log(str.match(/<script\b[^>]*>(.*?)<\/script>/gm));
}
You have to escape the forward slash like so: /.
myString.split(/(<script>|<\/script>)/)
I have an html string that I created with a template.
This string has an html table with a bunch of rows, I'd like to manipulate this string using jquery, for example to add some classes to some rows based on logic, or other manipulation and then have jquery return a string. However, it seems that jQuery only manipulates the DOM. But I don't want to post this string into the DOM yet.
var origString = "<table><tr id='bla'>...more html inside here...</tr></table>";
//Something like
var newString = $(htmlString -> '#bla').addClass('blaClass');
// this syntax is obviously wrong, but what I mean is I'm trying
// to look inside the string not the dom
Or maybe it's better to post this string into an invisible div first and then manipulate it with jquery?
Parse it to a variable, manipulate, then append:
var origString = "<table><tr id='bla'>...";
origString = $.parseHTML(origString);
$(origString).find("tr").addClass("test");
$("body").append(origString);
Concept demo: http://jsfiddle.net/6bkUv/
Yeah, you can add a class without appending it to the dom.
var origString = "<table><tr id='bla'>...more html inside here...</tr></table>",
newString = $('<div>'+origString+'</div');
newString.find('#bla').addClass('blaClass');
console.log(newString.html());
Yes, you can definitely manipulate a string with jQuery. Here is what the following code does:
Declares a div to wrap the string in
Wraps the string in the div and does the manipulation
Finally, produces the manipulated string
No interaction with the DOM whatsoever.
var htmlString = "<table><tr id='bla'>...";
var div = $('<div/>');
div.html( htmlString ).find( '#bla' ).addClass( 'class' );
var newString = div.html();
WORKING JSFIDDLE DEMO
//OUTPUT
Original: <table><tr id='bla'><td></td></tr></table>
New: <table><tbody><tr id="bla" class="class"><td></td></tr></tbody></table>
NOTE: Please note that if your table string does not have a tbody element jQuery will include it as that makes for valid table markup.
The answers were too complicated. The answer is just a dollar sign and some parentheses:
var queryObj = $(str);
So
var str = "<table><tr>...</tr></table>"
var queryObj = $(str);
queryObj.find('tr').addClass('yoyo!');
// if you use 'find' make sure your original html string is a container
// in this case it was a 'table' container
$("body").append(queryObj);
works just fine..
I have a dom node in variable and i want to remove all enter/line break, tabs between the html tags. Basically i want to minify it without using external library. How can i do it.
var target = document.getElementById('myid');
var wrap = document.createElement('div');
wrap.appendChild(target.cloneNode(true));
wrap contains the node..
Not elegant, but should work
target.innerHTML = target.innerHTML.replace(/\n|\t/g, ' ');
You could replace the line breaks with an empty string target.replace(/(\r\n|\n|\r)/gm,"");
What's the difference between:
var div = document.createElement('div');//output -> [object HTMLDivElement]
document.getElementById('container').appendChild(div);
and:
var div = '<div></div>';
document.getElementById('container').appendChild(div);//output -> <div></div>
Shouldn't both be the same? And if not, how do I get the second version to work?
The latter is simply a string containing HTML while the first is an object. For the first, you need appendChild while for the second, you need to append to innerHTML.
shouldn't both be the same? and if
not, how do i get the 2nd version to
work?
var div = '<div></div>';
document.getElementById('container').innerHTML += div;
With your JS/DOM engine, calling Element.appendChild with a string as an argument causes a new Text node to be created then added.
Your first example creates a <div> element. Your second example creates a text node with <div></div> as its contents.
Your second example is equivalent to:
var div = '<div></div>';
document.getElementById('container').appendChild(document.createTextNode(div));//output -> <div></div>
As Sarfraz Ahmed mentioned in his answer, you can make the second example work how you want it to work by writing:
var div = '<div></div>';
document.getElementById('container').innerHTML = div;
appendChild really does expect a HTMLDomNode of some kind, such as a HTMLDivElement, and not a string. It doesn't know how to deal with a string. You could do
document.getElementById('container').innerHTML += div;
but I really prefer the first version; and I'd rely more on it to behave the same across browsers.
appendChild is expecting an element so when you send it text, it doesn't know what to do. You might want to look into using a javascript library to ease some of that work, such as jQuery. Your code would be:
$('#container').append('<div></div>');
The simplest solution and support all browsers is:
var div = '<div></div>';
var parser = new DOMParser();
var myDiv = parser.parseFromString( html, "text/xml" );
Another solution may be:
var div = '<div></div>';
var tmpDiv = document.createElement('div');
tmpDiv.innerHTML = div;
elDiv = tmpDiv.childNodes[0]; //Now it can be used as an element
You can also use these to append/prepend an element to the DOM respectively:
var elem = document.documentElement.appendChild(document.createElement(element));
var elem = document.documentElement.prepend(document.createElement(element));
and use the elem variable to target the element (e.g):
elem.style.display = "block";
elem.style.remove();
elem.style.id = ...;
etc.