add element in certain place - javascript

When I use document.createElement javascript will add an element at bottom of body.
How can I add an element in certain place ? (with document.createElement property, I mean store in a new variable)

<html>
<head>
</head>
<script type="text/javascript">
var my_div = null;
var newDiv = null;
function addElement()
{
newDiv = document.createElement("div");
newContent = document.createTextNode("test");
newDiv.appendChild(newContent);
my_div = document.getElementById("org_div1");
document.body.insertBefore(newDiv, my_div);
}
</script>
<body onload="addElement()">
<div id='org_div1'> The text above has been created dynamically.</div>
</body>
</html>

When I use document.createElement javascript will add an element at
bottom of body.
No, an element is returned, but it is not attached to anything. You need to do that yourself:
var ptag = document.createElement('p');
ptag.innerHTML = "hello world";
var someplace = document.getElementById('some_element_id');
someplace.appendChild(ptag);
That's plain js; the jquery techniques are terser.

You can add dom/Element at the start or at the end of any DOM element using jquery.
See the below example
​
<!-- HTML CODE -->
<div id="item">
this is only test
</div>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
JQUERY Script:
$(document).ready(function(){
var item = "<span>New item</span>"
/* PrependTo */
$(item).prependTo('#item');
/* AppendTo */
$(item).appendTo('#item');
});
​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
see the jquery documentation here and here

Just add the element as a child of another one.
For instance:
HTML
<body>
<div id="container"></div>
...
[page content here]
...
</body>
JS
newdiv = $("<div>something</div>");
$("#container").append(newdiv);
See the documentation of append

uhm, I could be wrong, but if your using jQuery, are you looking for something like:
var newDiv = $("<div />");
Also if you have a jQuery list of elements (an object array) like $(".divs") which procs as [[Object Object], [Object Object]] (whereas each [Object Object] is a div element containing class .divs) you can add a new element to that list (without pasting to html body till ur rdy) by doing
$(".divs").add(newDiv);

Related

InnerHTML does not include the "frame" tag

I have a DOM element, which inside it has a node with the tag "frame".
But when I do innerHTML, the "frame" tag disappears. Why?
Example:
I have this string:
<div><p>Text</p><frame></frame></div>
If I want to put this string as the HTML of an element, the "frame" tag disappears:
var div = document.createElement('div');
div.innerHTML = str.trim();
Result:
<div><p>Text</p></div>
How can I resolve this?
You can't use <frame> inside <body> tag.
For that, write <frameset> instead of <body> and use <frame> inside <frameset></frameset>.
And, in the <body> tag( or DOM), you can use <iframe>.
Try this
var container = document.createElement('div');
var div = document.createElement('div');
var p=document.createElement('p');
p.innerHTML="Text";
var frame=document.createElement('frame');
div.appendChild(p);
div.appendChild(frame);
container.appendChild(div);
alert(container.innerHTML);
document.getElementById("mainContainer").appendChild(container);
alert(document.getElementById("mainContainer").innerHTML);
<div id="mainContainer"></div>

How to insert multi values to data-tag

I made a jquery filter function, that filtering the results by data-tags. like this:
<div class="resultblock" data-tag="ios">
<img src="images/osx.jpg" class="itemimg">
<div class="desc">
<div class="desc_text">
lorem ipsum
</div>
</div>
i just want to insert in the data-tag another tags to filter. like this:
data-tag="ios,android,windows"
How can i do that?
I am not sure I fully understand the question you are asking, but I think you could accomplish this via JS.
In your html add a script tag and then you just write some JS to edit or add html tags. Here is an example:
<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
</script>
Now to sort the data-tag:
just add this code to your HTML file.
<div id="div1">
</div>
<script>
var tag ="ios,android,windows"; //initialize variable
var data = tag.split(","); //this makes an array of ios,andrid,windows
var i = 0;
while (i < 3){
alert(i);
var para = document.createElement("p");
var node = document.createTextNode(data[i]);
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
i++;
}
</script>
The best way doing this is to use classes. Adding classes and removing them is much easier than other attributes. The classes should not overlap with other classes used for CSS for example. Adding a prefix to them is even better. Like this:
$(".filter-ios").hide(); // hide all ios elements
$("something").addClass("filter-windows"); // add the class windows to an element
$(".filter-ios").addClass("filter-apple"): // add the apple filter class to the ios filter class elements
$("something").hasClass("filter-samsung"); // check if an element has the filter class samsung
// ...
The classes .filter-* should be used for filtering only, they must not have any CSS attached to them, if there is already classes like that, then just change the prefix filter to something else!
I've just created a little object with two methods .add and .remove. It works like classList DOM method for adding and removing classes. If you add one value twice, it's added only once, also if you remove some not existing class, any error will occure. Hope you'll find it helpful.
var el = document.getElementById('myElem');
multiValues = {
add: function(elem,val){
if(elem.constructor.toString().search('HTML')===-1) return;
if(typeof val !=='string') return;
if(!elem.attributes['data-tag']) elem.setAttribute('data-tag');
var attr = elem.attributes['data-tag'];
var parsed = attr.value.split(',');
var isExist = parsed.some(function(a){
return a === val;
});
if(!isExist) parsed.push(val);
elem.setAttribute('data-tag',parsed.join(','));
},
remove: function(elem,val){
if(elem.constructor.toString().search('HTML')===-1) return;
if(typeof val !=='string') return;
if(!elem.attributes['data-tag']) return;
var attr = elem.attributes['data-tag'];
var parsed = attr.value.split(',');
parsed.some(function(a,b){
if(a===val){
parsed.splice(b,1);
}
elem.setAttribute('data-tag',parsed.join(','));
});
}
};
multiValues.add(el,'window');
multiValues.add(el,'window');
multiValues.add(el,'window');
multiValues.add(el,'android');
multiValues.remove(el,'a');
multiValues.remove(el,'b');
multiValues.add(el,'something');
console.log(el.attributes['data-tag'].value);
<div class="resultblock" data-tag="ios" id="myElem"></div>

Appending a div element using javascript

I am new to jQuery and I am practicing appending div elements. Here is my code:
<!doctype html>
<html lang="en">
<head>
<title>Div Id</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<script>
document.body.onload = addElement;
function addElement () {
// create a new div element
// and give it some content
var newDiv = document.createElement("div");
var newContent = document.createTextNode("This is a first division");
newDiv.appendChild(newContent); //add the text node to the newly created div.
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
}
</script>
<body>
<div id="div1">This is a second division.</div>
</body>
</html>
Output would be:
This is a second division.
But as per my implementation the output should be
This is a first division
This is a second division.
I am not able to figure where it is going wrong. Please someone help me out with this.
Thanks in advance.
onload is a property of the window object, not the document.body object.
This works:
window.onload = addElement;
actually it works.... try to move your javascript in the head of you html file
document.body.onload = addElement;
function addElement () {
// create a new div element
// and give it some content
var newDiv = document.createElement("div");
var newContent = document.createTextNode("This is a first division");
newDiv.appendChild(newContent); //add the text node to the newly created div.
// add the newly created element and its content into the DOM
var currentDiv = document.getElementById("div1");
document.body.insertBefore(newDiv, currentDiv);
}
<div id="div1">This is a second division.</div>
$('#div1').before('<div id=div0>This is a first division</div>')
demo
If you want Jquery it is as simple as this.
If you want to use jQuery you can check this fiddle:
$('body').prepend('<div>This is a first division</div>');

appendChild is not a function - what am I doing wrong?

I know this is a very common error, but I just can't figure out why this isn't working.
I want to change the value of a span dynamically. Simple, right? I've tried $span.innerHTML = "text" and $span.innerText = "text", which do nothing, but don't throw any errors. My most recent attempt looks like this:
var $resourceSpan = $("#divname"+dynamic_variable);
var stringVar = functionThatReturnsString();
while( $resourceSpan.firstChild ) {
$resourceSpan.removeChild( $resourceSpan.firstChild );
}
var textNode = document.createTextNode(stringVar);
$resourceSpan.appendChild( textNode );
Does anyone know why I'm throwing this error? Thanks
You are dealing with jQuery object, methods like removeChild() and appendChild() belongs to dom element not to the jQuery object.
To remove all contents of an element you can use .empty() and to set the text content of an element you can use .text(), but using .text() will replace existing content so in your case you can just use
var $resourceSpan = $("#divname" + dynamic_variable);
var stringVar = functionThatReturnsString();
$resourceSpan.text(stringVar);
Did you wanna do somethin like this?
<html>
<head>
<title>STACK OVERFLOW TESTS</title>
<style>
</style>
</head>
<body>
<span>HI, IM SOME TEXT</span>
<input type = 'button' value = 'Click me!' onClick = 'changeText()'></input> <!-- Change the text with a button for example... -->
<script>
var text = 'I AM THE NEW TEXT'; // The text to go in the span element
function changeText(){
var span = document.querySelector('span');
span.innerHTML = text;
}
</script>
</body>
</html>

create div horizontal layout element dynamically with javascript

How can I create <div horizontal layout></div> element dynamically using javascript?
i can create div element with document.createElement("div"); but how do I add horizontal layout to it?
<html>
<head>
<script type="text/javascript">
window.onload = function() {
newdiv = document.createElement("div");
newdiv.setAttribute('horizontal', '');
newdiv.setAttribute('layout', '');
document.body.appendChild(newdiv);
// You can insertBefore() too.
// Or... document.body.innerHTML = document.body.innerHTML + '<div horizontal layout></div>';
}
</script>
</head>
<body>
</body>
</html>
Some helpful links:
http://www.w3schools.com/jsref/met_document_createelement.asp
Adding elements to the DOM
Searching elements in DOM
How to add or update an attribute to an HTML element using JavaScript?
And so on.

Categories

Resources