Create a custom element in place where the code was initialized - javascript

I'm trying to create an element using JavaScript in place where the script was initialized.
I need to be able to just call a function for the element to appear just after the <script> tag in my HTML document.
I tried this code but I don't know how to actually create an element.
function createElement() {
var container = document.createElement('div');
container.setAttribute("class", 'someDiv');
document.createElement(container);
}
.someDiv {
height: 100px;
width: 100px;
background-color: gold;
}
<body>
<script>
createElement("div", "someDiv");
</script>
</body>

document.currentScript seems to have good browser support, and will give us the script element containing the code currently being executed.
If what you'd like to do is replace the current script with some other element, you use it like this:
<script>
const replacementText = document.createTextNode("hi, I'm the replacement!");
document.currentScript.parentNode.replaceChild(replacementText, document.currentScript);
</script>
If you simply want to insert an element after the current script, without replacing it:
<script>
const newText = document.createTextNode("hi, I'm new text!");
const currentScript = document.currentScript;
currentScript.parentNode.insertBefore(newText, currentScript.nextSibling);
</script>
Here's a more complex example using prewritten HTML:
<script>
const currentScript = document.currentScript;
const templateFragment = (function(){
const templateEl = document.createElement("template");
templateEl.innerHTML = `
<ul>
<li>Hi!</li>
<li>I am a list!</li>
</ul>
`;
return templateEl.content;
})();
currentScript.parentNode.insertBefore(templateFragment, currentScript.nextSibling);
</script>

You could use insertBefore and target insertion point as the script like so:
var script = document.querySelector('script:last-of-type');
var container = document.createElement('div');
document.body.insertBefore.insertBefore(script, container);

Using document.currentScript, we can get a reference to the script element where the code is running and then using .nextElementSibling, we can get the next sibling node that is an element. Finally, with .insertBefore and .appendChild(), we can insert the new element just before the element passed in as an argument (the sibling that was found earlier or body if none was found).
NOTE: Don't call your function createElement as it can cause a naming conflict with document.createElement().
This will insert an element just after the script element.
.someDiv {
height: 100px;
width: 100px;
background-color: gold;
}
<head>
<script>
function create(type, style) {
var container = document.createElement(type);
container.classList.add(style); // Best way to add a class
container.textContent = "Hello!";
let sibling = document.currentScript.nextElementSibling;
if(sibling){
// Insert the new element before the next sibling
sibling.parentNode.insertBefore(sibling, container)
} else {
// Insert the new element at the end of the body
document.body.appendChild(container);
}
}
</script>
</head>
<body>
<p>The new element should be right below this.</p>
<script>
create("div", "someDiv");
</script>
<p>The new element should be right above this.</p>
</body>

You can use .insertBefore() to add some element before the next sibling of your script. To reference your script, you could add an id attribute to it:
.someDiv {
height: 100px;
width: 100px;
background-color: gold;
}
<body>
<p>I'm inside the body, before the script TAG</p>
<p>New element should appear just after this text...</p>
<script id="myScript">
function createElement()
{
var container = document.createElement('div');
container.setAttribute("class", 'someDiv');
var script = document.getElementById("myScript");
script.parentNode.insertBefore(container, script.nextSibling);
}
createElement();
</script>
<p>I'm inside the body, but after the script TAG</p>
</body>

Related

jQuery nest appends

is it possible to nest appends in jQuery??
I tried to do this:
var div = $('#ui-container');
var div2 = div.append( $('<div/>').addClass('second') );
var div3 = div2.append( $('<div/>').addClass('third') );
I want this:
<div id='ui-container'>
<div class='second'>
<div class='third'></div>
</div>
</div>
But I get this:
<div id='ui-container'>
<div class='second'></div>
<div class='third'></div>
</div>
You have to do it like below,
var div = $('#ui-container');
var div2 = $('<div/>').addClass('second').appendTo(div);
var div3 = div2.append($('<div/>').addClass('third'));
by using .appendTo(). Because .append() will return the object over which the append function was called. That is why you are seeing such result in your case.
#Rajaprabhu Aravindasamy has the correct answer. I thought I would go a little more in depth and add a jsfiddle.
Use appendTo() instead of append. Here's a quote from http://api.jquery.com/appendto/
The .append() and .appendTo() methods perform the same task. The major difference is in the syntax-specifically, in the placement of the content and target. With .append(), the selector expression preceding the method is the container into which the content is inserted. With .appendTo(), on the other hand, the content precedes the method, either as a selector expression or as markup created on the fly, and it is inserted into the target container.
Here's the markup:
var div = $('#ui-container');
var div2 = $('<div>div2<div/>').addClass('second').appendTo(div);
var div3 = $('<div>div3<div/>').addClass('third').appendTo(div2);
Try:
var div = $('#ui-container');
var div2 = $('<div/>').addClass('second');
div2.append( $('<div/>').addClass('third') );
div.append(div2);
jquery methods typically return the DOM node that they are being called on.
Therefore
var div2 = div.append( $('<div/>').addClass('second') ); // returns $('#ui-container')
It is also standard to reference DOM elements with a $ such as $div.
Here is a verbose solution
// Grab container
$div = $('#ui-container');
// Create first child
var div2 = '<div class="second"></div>'
// Append .second to #ui-container
$div.append(div2);
// Grab .second from the DOM
var $div2 = $('.second');
// Create grandchild element
var div3 = '<div class="third"></div>'
// Append to .second
$div2.append(div3)
codepen
All of your variables div, div2 and div3 refer to the same element $('#ui-container'). Easiest way to understand what you did would be to rename your variables, so you can see what happens:
/* What you did is this: */
var container = $('.result1');
var containerWithSecondAppended = container.append( $('<div/>').addClass('second') );
var containerWithThirdAppended = containerWithSecondAppended.append( $('<div/>').addClass('third') );
/* What you wanted to do is this: */
var div = $('.result2');
var div2 = $('<div/>').addClass('second');
var div3 = $('<div/>').addClass('third');
div.append( div2.append(div3) );
div {
padding: 10px;
border: 1px solid black;
}
.result {
margin: 10px;
padding: 10px;
}
.second {
background: none yellow;
}
.third {
background: none green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="result result1"></div>
<div class="result result2"></div>
Also on Fiddle.
jQuery append method will return a jQuery element, the one that was appended (changed).

How to dynamically add a CSS class and implement its style in JavaScript

Hi I'm new to JavaScript and CSS and I would like to create a JavaScript function that dynamically applies the style properties that are defined inside this function to a specific element.
Please check my code below, I have managed to create the element and add the class to that element but I'm struggling to implement the style properties inside this function.
function highlight(){
var styl = document.querySelector("#element_to_pop_up");
styl.style.cssText = " background-color:#fff;border-radius:15px; color:#000;display:none;padding:20px;min-width:30%;min-height: 30%;max-width:40%; max-height: 40%;";
styl.className = styl.className + "b-close";
//.b-close{
//cursor:pointer;
//position:absolute;
//right:10px;
//top:5px;
//}
}
Please any help will be highly appreciated.
If you want to add a style class to your page and write its style content, you should create it first then put it in a <style> tag, so you can use it later.
This is your way to go:
function highlight() {
var styl = document.querySelector("#element_to_pop_up");
//Create StyleSheet
var styleSheet = document.createElement("style");
var text = document.createTextNode("\n.b-close {\n cursor:pointer;\n position:absolute;\n right:10px;\n top:5px;\n}");
//Put the style on it.
styleSheet.appendChild(text);
//Append it to <head>
document.head.appendChild(styleSheet);
//Apply it
styl.className = styl.className + " b-close";
}
<div onclick="highlight()" id="element_to_pop_up">bla bla bla</div>
Create a Style Sheet Element.
Put the style on it.
Append it to the head of the document.
Use this style or apply it to element.
EDIT:
If you will pass the style top and right values as parameters to the function just do the following:
function highlight(right, top) {
var styl = document.querySelector("#element_to_pop_up");
var styleSheet = document.createElement("style");
var text = document.createTextNode("\n.b-close {\n cursor:pointer;\n position:absolute;\n right: "+right+"px;\n top: "+top+"px;\n}");
styleSheet.appendChild(text);
document.head.appendChild(styleSheet);
styl.className = styl.className + " b-close";
}
Use jquery insted on javascript.
$(selector).css("width":"100%").css("height","100px");
You can just add a CSS class (and style it in your stylesheet instead of your javascript).
Here is an example (there are multiple way to do it but I don't know what your try to achieve exactly) :
function highlight(){
var target = document.getElementById("header");
target.className = target.className + " highlighted";
}
var btn = document.getElementById('add-class');
btn.addEventListener('click', highlight);
.highlighted {
/*Your CSS*/
background-color: red;
}
<h1 id="header">Lorem</h1>
<button id="add-class">Click me</button>
Edit: If you want to use jQuery, it's even simpler :
$(document).ready(function() {
$('#add-class').on('click', function() {
$('#header').toggleClass('highlighted');
});
});
.highlighted {
/*Your CSS*/
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 id="header">Lorem</h1>
<button id="add-class">Click me</button>

What is the easiest way to add an element to html through javascript

It seems there are many ways to do this, however, none of them make sense to me. If anyone can give me an example of how to add a tag and edit its attributes (no document.write mess) that works in all common browsers BUT IE, that would be great.
EDIT I simply do not care if it works in IE or not. If it does, fine but I dislike IE so much anyway I will just ask people to change browsers since other stuff on the page I am creating does not work in IE.
Here is the easiest example of how to create a <div> element and add it to the layout.
var el = document.createElement("div"); // creating element
el.setAttribute("class", "myClass"); // setting attribute "class"
el.innerHTML = "Text"; // adding text inside the element
document.body.appendChild(el);​ // appending new element to page body
DEMO: http://jsfiddle.net/XVaqY/
To make it not working in IE add any browser check. Something like that:
function isIE() {
return (navigator.appName == "Microsoft Internet Explorer");
}
Here is a working example of adding a DIV with javascript
http://jsfiddle.net/wp2Re/
<html>
<head>
<title>Javascript Create Div Element Dynamically</title>
<style type="text/css">
.dynamicDiv {
width: 200px;
height: 100px;
border: solid 1px #c0c0c0;
background-color: #e1e1e1;
font-size: 11px;
font-family: verdana;
color: #000;
padding: 5px;
}
</style>
<script type="text/javascript" language="javascript">
function createDiv() {
var divTag = document.createElement("div");
divTag.id = "div1";
divTag.setAttribute("align", "center");
divTag.style.margin = "0px auto";
divTag.className = "dynamicDiv";
divTag.innerHTML = "This HTML Div tag created "
+ "using Javascript DOM dynamically.";
document.body.appendChild(divTag);
}
</script>
</head>
<body>
<p align="center">
<b>Click this button to create div element dynamically:</b>
<input id="btn1"
type="button"
value="create div"
onclick="createDiv();" />
</p>
</body>
</html>
First, you create the element with document.createElement() and save it to a variable. At this point it is not in the DOM yet.
Then, change its attributes as much as you like, and then insert it into the DOM at any point you like. In my example, it will insert a DIV element with the id of elementid into the end of the body tag.
var newDiv = document.createElement("div");
newDiv.id = "elementid";
document.body.appendChild(newDiv);
Here are a few methods to add content to the DOM:
Using the W3C recommended approach:
var heading = document.createElement("h1");
heading.createTextNode("Foobar");
heading.className = "semantic-class-name-goes-here";
heading.setAttribute("aria-something-here", "bar");
Using innerHTML:
document
.innerHTML("<h1 class='semantic-class-name-goes-here' aria-something-here='bar'>Foobar</h1>");
Using jQuery:
var heading = $("h1")
.addClass("semantic-class-name-goes-here")
.attr("aria-something-here", "bar");
$(document).append(heading);
Assuming you want to exclude all IE versions, using this trick from webreflection blog you could do
if (!(!+"\v1")) {
var el = document.createElement("div");
...
document.body.appendChild(el);
}
Alternatively, another condition to detect IE could also be
if (!top.execScript) { ... }
or even
var isIE = /*#cc_on!#*/!1;
if (isIE) { ... }
but to be honest they're so hacky for me.
Anyway, if you specify the technical reason for excluding IE and tell us what kind of functionality are you trying to accomplish, probably it's possibile to give you a safer way to do this task, based on a specific IE limit (feature dection is better than browser sniffing).

add element in certain place

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);

JavaScript Getting ID of A Div

I have a div box with its id and an textarea.
When I click on my div box I should get div ID through Javascript and get it printed on the textarea. I have tried but its not working. when I click the text area it says "undefined". Kindly help me.
Here is the code:
<html>
<head>
<script type="text/javascript">
function get_id()
{
var divEls = document.getElementsByTagName("div");
var textEl = document.getElementById("mytextarea");
textEl.value=divEls.id;
}
</script>
</head>
<body>
<div id="mydiv" onclick="get_id()" style='border-width:1px;border-color:#C0C0C0;border-style: solid;background-color:#C0C0C0;width:130px;height:10px;'>
</div>
<textarea id="mytextarea"> </textarea>
</body>
</html>
getElementsByTagName returns a nodeList of DOM nodes, which acts like an array.
You'll need to select the first item in the node list before you can access the node's ID:
textEl.value = divEls[0].id;
Alternatively, you could have passed this to get_id():
function get_id(node) {
var textEl = document.getElementById('mytextarea');
textEl.value = node.id;
}
onclick="get_id(this)"
But honestly, all of the JavaScript should be external to your HTML file. HTML belongs in .html files, CSS belongs in .css files and JS belongs in .js files.
//i haven't checked this code, and you probably want to modify it to be more generic.
window.onload = function () {
var myDiv, myTextArea;
myDiv = document.getElementById('mydiv');
myTextArea = document.getElementById('mytextarea');
myDiv.onclick = function () {
myTextArea.value = myDiv.id;
};
};
Rewrite your code as below:
<html>
<head>
<script type="text/javascript">
function get_id(element) {
var textEl = document.getElementById("mytextarea");
textEl.value = element.id;
}
</script>
</head>
<body>
<div id="mydiv" onclick="get_id(this)" style='border-width: 1px; border-color: #C0C0C0;
border-style: solid; background-color: #C0C0C0; width: 130px; height: 10px;'>
</div>
<textarea id="mytextarea"> </textarea>
</body>
</html>
When you use getElementsByTagName, you get ALL of the elements with that tag as an array.
If you want the first DIV then you need to add [0] this way:
var divEls = document.getElementsByTagName("div")[0];
The remaining code is ok.
getElementsByTagName returns an array even if it contains only one object. You should access it like this:
function get_id()
{
var divEls = document.getElementsByTagName("div");
var textEl = document.getElementById("mytextarea");
textEl.value=divEls[0].id;
}
divels is, as the plural is indicating, an Array (correct: a NodeList), which has no id property. Its items have, so eg. textEl.value=divEls[0].id; will work (if the List is empty, this will throw an error).
try this function
function get_id()
{
var divEls = document.getElementsByTagName("div");
var textEl = document.getElementById("mytextarea");
textEl.value=divEls.item(0).id;
}
Ok I figured it out. document.getElementsByTagName("div") will return all the elements which have tag name div as an array of nodes. Here in your code there is only one div element hence first element is div itself. As in an array first element has number index = 0 so we can get first by document.getElementsByTagName("div")[0] or in your code divEls[0], and then we can get its id by simply getting divEls[0].id. Now as we have got the div id we can set the value of text area equal to this div id as: textEl.value = divEls[0].id Here is your code with changes. Hope this Helps
<html>
<head>
<script type="text/javascript">
function get_id()
{
var divEls = document.getElementsByTagName("div");
var textEl = document.getElementById("mytextarea");
/*get the first item in the nodelist ie divEls[0] = document.getElementsByTagName("div")[0] and then get its id by
its id by divEls[0] */
textEl.value = divEls[0].id;
}
</script>
</head>
<body>
<div id="mydiv" onclick="get_id()" style='border-width:1px;border-color:#C0C0C0;border-style: solid;background-color:#C0C0C0;width:130px;height:10px;'>
</div>
<textarea id="mytextarea"> </textarea>
</body>
</html>

Categories

Resources