change name of DIV width JavaScript - 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");

Related

How to create an element and set unnamed parameters

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

With jQuery, how do you add an element before another element without making copies?

I have a situation where I need to add a sibling element to a jQuery object that is stored in a variable. I need the added element to be the previous sibling of that jQuery object.
The simplified version would look something like this https://jsfiddle.net/sjncgaLf/4/
$(document).ready(function() {
var test = $('<div class = "test">test</div>');
var el = $('<div class = "el">el</div>');
//I want to add el before test (without making a copy)
//and then append the selector (el + test) to the DOM
el.before(test);
$("body").append(test);
});
Clearly, based on the jsfiddle, this code does not achieve the desired affect. My goal is to achieve a result like this
<div class = "el">el</div>
<div class = "test">test</div>
Without copying the original elements. I've read the .before, .insertBefore, and .add documentation thoroughly, and it looks like none of those will produce exactly what I want here.
Thanks in advance.
EDIT:
I suppose need to be more clear. I'm making a calendar 1 month at a time. I need to start with a variable like $markup, and add weeks to it until I've added each day in the month. I also need to add a label to the month, like "July, 2016". So, before I append any weeks to my $markup variable, or append anything to the DOM, I want my $markup to look like this
<div class = "label">July 2016</div>
<div class = "CalendarWeek"></div>
I'll then iterate over the days of that month and add as many CalendarWeek and CalendarDay as need be.
try like this.
$("body").append(el,test);
the updated fiddle : https://jsfiddle.net/sjncgaLf/14/
You can do that using the jQuery - insertBefore method.
I have updated your jsFiddle
$(document).ready(function() {
// create elements
var test = $('<div class = "test">test</div>');
var el = $('<div class = "el">el</div>');
// add the first element
$("body").append(test);
// insert the second element
el.insertBefore(test);
});
Based on your update, you just need to edit your variable, not worry about appending data in order.
So for your $markup variable, if it already has data and you want to add your month label at the beginning, just use:
$temp = $label + $markup;
$markup = $temp;
To add weeks or day data to the end of your $markup variable, just use:
$markup = $markup + $day;
Once you've got the entire variable built the way you like you can use jQuery to append it where you want.

get the html of element itself using jquery .html()

How to get the html of element itself using Jquery html. In the below code I would like get the input element inside div using JQuery as shwon below
<div id="content">content div</div>
<input type='text' id="scheduledDate" class="datetime" />
$(function() {
console.log($('#scheduledDate').html('dsadasdasd'));
$('#content').html($('#scheduledDate').html());
});
EDIT:
Can I get the $("#scheduledDate") as string which represent the real html code of the input box, because my final requirement is I want to pass it to some other SubView( I am using backboneJS) and eventually use that html code in a dust file.
My original requirement was to get that input field as string so that I can pass it to some other function. I know, if I keep it inside a DIV or some other container, I can get the html by using .html method of JQuery. I dont want use some other for that purpose. I am just trying to get html content of the input box itself using it's id.
If you want to move the input element into div, try this:
$('#content').append($('#scheduledDate'));
If you want to copy the input element into div, try this:
$('#content').append($('#scheduledDate').clone());
Note: after move or copy element, the event listener may need be registered again.
$(function() {
var content = $('#content');
var scheduledDate = $('#scheduledDate');
content.empty();
content.append(scheduledDate.clone());
});
As the original author has stated that they explicitly want the html of the input:
$(function() {
var scheduledDate = $('#scheduledDate').clone();
var temporaryElement = $('<div></div>');
var scheduleDateAsString = temporaryElement.append(scheduledDate).html();
// do what you want with the html such as log it
console.log(scheduleDateAsString);
// or store it back into #content
$('#content').empty().append(scheduleDateAsString);
});
Is how I would implement this. See below for a working example:
https://jsfiddle.net/wzy168xy/2/
A plain or pure JavaScript method, can do better...
scheduledDate.outerHTML //HTML5
or calling by
document.getElementById("scheduledDate").outerHTML //HTML4.01 -FF.
should do/return the same, e.g.:
>> '<input id="scheduledDate" type="text" value="" calss="datetime">'
if this, is what you are asking for
fiddle
p.s.: what do you mean by "calss" ? :-)
This can be done the following ways:
1.Input box moved to the div and the div content remains along with the added input
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
$("#content").append($inputBox);
});
2.The div is replaced with the copy of the input box(as nnn pointed out)
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
var $clonedInputBox = $("#scheduledDate").clone();
$("#content").html($clonedInputBox);
});
Div is replaced by the original input box
$(document).ready(function() {
var $inputBox = $("#scheduledDate");
$("#content").html($inputBox);
});
https://jsfiddle.net/atg5m6ym/4485/
EDIT 1:
to get the input html as string inside the div itself use this
$("#scheduledDate").prop('outerHTML')
This will give the input objects html as string
Check this js fiddle and tell if this is what you need
https://jsfiddle.net/atg5m6ym/4496/

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

Prototype function different id elements of the same class

I'm making this prototype script to work:
function removing () {
*var ids = $$('.class').collect(function(el) { return el.id; });* //array of ids, not used by now
var data = $$('.class').pluck('innerHTML');
var wanted_count = 10;
var output = cutHtmlString(data, wanted_count);
$$('.class').invoke('replace', output + '...');
}
on this markup:
<div class="class" id="id1">content 1</div>
<div class="class" id="id2>content 2</div>
<div class="class" id="id3>content 3</div>
cutHtmlString is a function that cut html strings keeping tags and I want to apply it to every different div content. I create 'data' variable (by innerHTML) from general $$(.class) and then I execute cutting by a words count (var wanted_count) into 'output' var.At the end I replace the original element (by $$.class again) with its new cut content.All works great except for one issue: using only $$(class) makes only the first element content to be considered and replaced to every others.I need to identify elements by ids too, I guess..thus I added the commented function upon (collect) but I don't know how to join my target..By now I only got to this results:
this is the content of firts 'class'
div...(cut)this is the content of firts 'class' div...
this is the content of firts 'class' div...
while I want to get:
this is the content of first 'class'
div...
this is the content of second 'class' div...
this is the content of third 'class' div...
thanks guys and an appreciation to this great community whole
I believe you are mixing working on a collection of elements with working on a single element. It's been a while since I've been in Prototype, but have you tried to work on very individually so output is scoped to the element you are replacing:
function removing () {
var data, output, wanted_count = 10;
$$('.class').each(function(element){
output = cutHtmlString(element.innerHTML, wanted_count);
element.replace(output + '...');
});
}
Invoke only woks if your padding the same variables to each element. You need to use each.
Also I think you want to use update and not replace.
try this.
function removing() {
$$('.class').each(function(el){
var output = cutHtmlString(el.innerHTML, 10);
el.update(output + '...');
});
}

Categories

Resources