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.
Related
When I do this:
var elem = $(".region_box");
text = elem.find(".my_text").html();
I can get text from the first element deep below "elem" with class "my_text" which it finds.
But there are many elements of the class "actual_text" below elem and I want to combine the text from all of them. How would I do it?
I am new to jQuery and I searched around for solution for long time, but neither of them worked for me. Perhaps I am using this each() function incorrectly. I would very much appreciate any help.
You can use the jQuery.each
var text = '';
var elms = $(".region_box .my_text").each(function () {
text = text + $(this).text(); // use .html() if you actually want the html
});
Define a variable to hold the new string, select all of the elements you wish to extract, chain that with .each() and add the contents of the text node for that element to the variable you created to hold the new string.
(Demo)
var text = "";
$(".region_box .my_text").each(function(){ text += " " + $(this).text(); });
try something using jquery .map() method like this,
text = $('.region_box').find('.my_text').map(function() {
return $(this).text();
}).get().join(',');
As the site said, "As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array."
I tried to add same element to the HTML document multiple times, but it doesn't work, I don't know the reason. The code is following:
<html>
<body>
<div>Very</div>
<div>Secret</div>
<script>
var elem = document.createElement('div')
elem.innerHTML = '**Child**'
document.body.insertBefore(elem,document.body.lastChild);
document.body.insertBefore(elem,document.body.lastChild);
document.body.insertBefore(elem,document.body.lastChild);
</script>
</body>
</html>
why the result is
Very
Secret
**Child**
instead of
Very
Secret
**Child**
**Child**
**Child**
DOM manipulation methods like insertBefore and appendChild move elements if they are already in DOM tree. That's why you end up with only one node appended to the end.
If you want to create three different nodes, then you have a couple of options.
1). Cloning node. Using cloneNode you can append cloned node instead of original:
var elem = document.createElement('div')
elem.innerHTML = '**Child**';
document.body.insertBefore(elem.cloneNode(true), document.body.lastChild);
Demo: http://jsfiddle.net/xh3nqe85/
2). String as template. You can append HTML string instead of NodeElement. The most convenient method for this manipulation is insertAdjacentHTML:
var elem = '<div>**Child**</div>';
document.body.lastElementChild.insertAdjacentHTML('afterend', elem);
document.body.lastElementChild.insertAdjacentHTML('afterend', elem);
document.body.lastElementChild.insertAdjacentHTML('afterend', elem);
Demo: http://jsfiddle.net/xh3nqe85/1/
You should create the element for three times.
In the way you did you are just creating one element and setting it three times:
function myFun() {
var elem = document.createElement('div')
elem.innerHTML = '**Child**'
return elem;
}
document.body.insertBefore(myFun(), document.body.lastChild);
document.body.insertBefore(myFun(), document.body.lastChild);
document.body.insertBefore(myFun(), document.body.lastChild);
http://jsfiddle.net/6zppunvv/
When you append a node to a different node, you aren't cloning it.
See the Node.cloneNode method to actually clone a node.
Try to clone the node.
var elem = document.createElement('div')
elem.innerHTML = '**Child**'
document.body.insertBefore(elem,document.body.lastChild);
document.body.insertBefore(elem.cloneNode(true),document.body.lastChild);
document.body.insertBefore(elem.cloneNode(true),document.body.lastChild);
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 paragraph with text and anchors.
Given an anchor $myAnchor within the paragraph, I can get the immediately following one:
$nextAnchor = $myAnchor.next('a');
How do I get the text/HTML between these two anchors?
Here you go:
$myAnchor[0].nextSibling.nodeValue
Live demo: http://jsfiddle.net/3Xp6G/1/
So, nextSibling will give you a reference to the next sibling node (which is a Text node), and then nodeValue will return the text-content of that Text node.
Btw [0] is required after $myAnchor because nextSibling is a property of DOM nodes, not jQuery objects, and [0] returns the first DOM element from the jQuery object.
You can also use .trim() at the end to get rid of the useless white-space (if there is any).
Edit: misunderstood question.
See here: http://jsfiddle.net/RkEwR/
Use .contents()
To get the text between 2 anchors o can do something like this.
var a1 = $('#anchor1');
var a2 = $('#anchor2');
var contents = a1.parent().contents();
var s, e;
for(var i = 0; i<contents.length; i++){
if($(contents[i]).is(a1)){
s = i
}
if($(contents[i]).is(a2)){
e = i
}
}
var text = contents.slice(s + 1,e).text().trim();
If you know that there is only one element in betewwen u can use the nextSibling method described.
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.