How to create an element and set unnamed parameters - javascript

I'm used to creating html-elements in JavaScript like so:
var div = document.createElement('div');
div.setAttribute('id', 'some_id');
div.setAttribute('custom_attribute', 'some_other_value');
But what if my div should look like:
<div class="uk-grid" data-uk-sortable data-uk-grid-margin>
Please, pay attention to these two parameters (or should I call it another way?) - data-uk-sortable and data-uk-grid-margin. How can I create them programmatically? PS. I'm not even sure, whether I should call these parameters "unnamed". Probably, there is a better convention.

The following
<div class="uk-grid" data-uk-sortable data-uk-grid-margin>
Is the same as
<div class="uk-grid" data-uk-sortable="" data-uk-grid-margin="">
var div = document.createElement('div');
div.setAttribute('id', 'some_id');
div.setAttribute('data-uk-sortable', '');
div.setAttribute('data-uk-grid-margin', '');
// just for the demo
document.write(div.outerHTML.replace(/</, '<'));

div.setAttribute('data-uk-grid-margin', '');

Related

Ondragstart Attribute doesn't appear when created dynamically

I have my images in an array and I have to create a div with an image inside dynamically and that image has to had the ondragstart attribute but I can't make it work. I used everything.
function showOptions(i,j){
var div= document.createElement("div");
var img = document.createElement("img");
var divOptions= document.getElementById('options');
div.id = "div"+i+j;
img.src = imgArray[i][j].src;
div.className="options";
img.draggable= true;
img.ondragstart="dragStart_handler(event)";
divOptions.appendChild(div);
div.appendChild(img);
And this is the html part:
<div id='options'> <!-- Here should be the divXX and the img --> </div>
I also used the methods addEventListener and attachEvent. But nothing seems to work. Can I write the div and the image to the HTML in another way?
This assignment is bad:
img.ondragstart="dragStart_handler(event)";
You're assigning a string to a property that expects a function.
This should work:
img.ondragstart = dragStart_handler;
This is better:
img.addEventListener("dragstart", dragStart_handler); // note: no "on"
I think you're confusing the convenience syntax where you write a little bit of JavaScript in HTML, like:
<img ondragstart="dragStart_handler(event);" />
I think you can also pass a string into functions like setTimeout:
setTimeout("dragStart_handle", 100);
This works because JavaScript expects a function and will eval the string argument.
I would avoid this sytnax.
img.setAttribute("ondragstart", "dragStart_handler(event)");
Let me know if that works for you. Works for me whilst img.ondragstart does not.

change name of DIV width JavaScript

I am using following code:
...
<div id="divcontainer1">
...
<div id="divcontainer2">
...
</div>
</div>
...
Now, I want change "divcontainer2" at a later point of time in the Div "divcontainer3".
What is the right way to check is exist divcontainer2 and when true,
change in divcontainer2 width javascript ?
Thank you,
Hardy
It is probably not nest practice but you can do this by changing the .outterHTML of the element. You would likely want to improve on this but here is a quick example. The last line checks if div 2 exists.
var div2 = document.getElementById("div2");
var html = div2.outerHTML;
var idx = html.indexOf(">");
var newtag = html.substring(0, idx).replace("div2", "div3");
div2.outerHTML = newtag + html.substring(idx, html.length - 1);
var contents = document.getElementById("div3").innerHTML;
alert(document.getElementById("div2") != undefined);
All you do is
get the element .outterHTML
get the substring representing the tag.
Replace the text that defines it
Set the .outterHTML tag to our new string
Now you have a newly named div that keeps all of its attributes, position in the parent and content.
The alert line is how you check for the existence of an object.
I don't believe that there is a "proper" way to do this, however I would store the contents of divcontainer2 in a variable, and then do something like this
var containerOfDivContainer2 = document.getElementById("containerofdiv2");
containerOfDivContaier2.innerHTML = "<div id='divcontainer3'>"/* insert div contents */+"</div>";
Of course, this requires you to put divcontainer2 in a div called containerofdiv2 but it works.
If using jQuery, this will do it:
$('#divcontainer2').attr('id','divcontainer3');
But you shouldn't be changing IDs. Use classes instead and then use the jQuery's toggleClass() function, like:
<div id="divcontainer1">
...
<div id="divcontainer2" class="style1">
...
</div>
$('#divcontainer2').toggleClass("style1 style2");

Javascript - Insert element at script position

How do I insert element at script location (not to rely on div's id or class), for example
<div class="div">
<script src='//remotehost/js/addDivSayHello.js'></script>
</div>
where addDivSayHello.js will insert div child <div>hello</div>, result example:
<div class="div">
<div>hello</div>
<script src='//remotehost/js/addDivSayHello.js'></script>
</div>
I tried searching inside Stackoverflow but found nothing.
You can use insertBefore method. Something like this:
var div = document.createElement('div'), // Create a new div
script = document.scripts[document.scripts.length - 1]; // A reference to the currently running script
div.innerHTML = 'Hello'; // Add some content to the newly-created div
script.parentElement.insertBefore(div, script); // Add the newly-created div to the page
A live demo at jsFiddle. Notice, that you can use external scripts as well.
You could use insertAdjacentHTML: https://developer.mozilla.org/en-US/docs/Web/API/Element.insertAdjacentHTML
var node = document.querySelector('script[src="js/addDivSayHello.js"]');
node.insertAdjacentHTML('beforebegin', '<div>hello</div>');
$("div.div").prepend('<div>hello</div>');
You have to call the script at some point
i like to use jquery to add an element http://api.jquery.com/append/
you have to say where do you want to add :
$(".div")
and what should happen there:
.append("<div>Hello</div>")
so its look like that:
$(".div").append("<div>Hello</div>")
Another solution that doesn't wrap everything inside a div and that can be re-used several times without implications:
function insertHtmlToDocumentAtCurrentScriptPosition(htmlStr)
{
var scriptTag = document.getElementsByTagName('script');
scriptTag = scriptTag[scriptTag.length - 1];
var parentTag = scriptTag.parentNode;
parentTag.innerHTML += htmlStr;
}
The function takes html as string, so call it like:
insertHtmlToDocumentAtCurrentScriptPosition(`<p>Hello</p>`);

InnerHTML + find() not working

I've been searching and trying different codes, but I don't came up to a solution.
This script i'm trying to create do this:
When the user clicks inside a div with class="Box". The program will save in a variable the content of the Box.
var boxContent = $(this).parents('.Box')[0].innerHTML;
So, the value of the variable boxContent now (acording to my html output will be) returns the hole div that the user clicked:
<div class="Box">
<div class="URL_ID">
<span>http://test.com</span>
<span id="ID">3232434</span>
</div>
<div class="info">
</div>
<div class="secondLink">
</div>
</div>
Now what i'd like to take is the div to process later and do an append in a table. So i tried to use find(), but doesn't work...
var url = boxContent.find('.BoxSongUrl');
What can i do??
Thanks in advance.
Your statement:
So, the value of the variable boxContent now (acording to my html output will be) returns the hole div that the user clicked:
Is not true. innerHTML returns a string of the markup html inside the element. To use the Jquery's .find() method, you have to actually select the Jquery object:
var url = $(this).parents('.Box').find('.BoxSongUrl');
You can use clone to retain a copy of the first '.Box' element at the time the query is run.
var boxContent = $(this).parents('.Box').first().clone();
Then, you can use the find method on boxContent
var url = boxContent.find('.BoxSongUrl');
EDIT:
If you would rather not clone the whole jQuery object you would save the html and re-parse it before calling find.
var boxContent = $(this).parents('.Box').first().html();
Then, re-parse the HTML into a jQuery object:
var url = $(boxContent).find('.BoxSongUrl');

How do you enclose unknown HTML in a div with plain Javascript?

I have an HTML page that has varying types of content. I would like to make a javascript function that when run encloses anything inside the <body> tag with a <div id="content-container">. Then I want to be able to add a <div id="verifying"></div> that new <div>. I think I know how to do this with jQuery, but I need to do it with plain Javascript.
Any idea as to how this would be done?
This is how I might do it.
var body = document.body;
var contentContainer = document.createElement('div');
contentContainer.id = 'content-container';
var node;
while (node = body.firstChild) {
contentContainer.appendChild(node);
}
body.appendChild(contentContainer);
var verifying = document.createElement('div');
verifying.id = 'verifying';
contentContainer.appendChild(verifying);
jsFiddle.
I haven't tested, but I imagine that you can take the innerHTML of document and set it to be itself along with whatever wrapper string (or div) you want.
Something along the lines of:
body = methodToLocateBodyInTheDom();
body.innerHTML = "<div id='content-container'>" + body.innerHTML + "</div>"
There are probably better ways, but I think something of that nature sure work.

Categories

Resources