read html object and replace javascript properties with read values - javascript

I have a JavaScript parameter object with some HTML content in the following structure.
function (type, content, title) {
// Replace code should go here
options = {
"data-onclick": null;
"data-progress": false;
}
}
The content of the content object looks as follows:
<div id=content data-onclick="onclickValue" data-progress="true"></div>
I would like to read out the data- parameters from the HTML div and assign them to replace the same named function in the JavaScript function.
All of this should happen at the top of my JavaScript function and replace the properties in the same function.
Thanks for any help or pointers how to achieve this, I am not very skilled at JavaScript.

// first select the html element
var element = document.getElementById('content');
// use the getAttribute('attribute-to-get') method to get your attributes
var options = {
'data-onclick': element.getAttribute('data-onlick'),
'data-progress': element.getAttribute('data-progress')
};
// consider using a hidden input field rather than hiding the element with css
// this is best practice
<input type="hidden" id="content" data-onclick="onclickValue" data-progress="true" />

What I would do (assuming jQuery):
create an invisible div in your html
set the innerHTML of the div
set the attributes from those of the invisible div to your object:
$("#invisible").html(content);
options["data-onclick"] = $("#invisible").find("#content").attr("data-onclick");
options["data-progress"] = $("#invisible").find("#content").attr("data-progress");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="invisible" style="display: none;">

Related

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/

How to move onclick code to one place using something like class. Repeated code at various html tags

onclick="triggersTracking($(this).attr('a'),$(this).attr('b'),$(this).attr('c'),Enum.BtnSellerView)"
I have this line at various HTML tags/buttons. I want to move this code to one place for better maintainability. The problem is with third/last attribute i am passing since its Enum, it has different values being passed from different tag elements.
How can i move it to one common place where it would get invoke. For example I could have made a class if i have had just these (this).attr since its common for every tag.
You can do like
Give all the elements a common class name
Then add a data attribute, "data-enum" to each tag with corresponding value.
Then you can write the code like this,
$(".className").click(function () {
var a = $(this).attr('a');
var b = $(this).attr('b');
var c = $(this).attr('c');
var enum = $(this).data('enum');
});
You can use jquery to get this:
$("body").on("click", "someClass", function() {
//code here
});
you don't need to write $(this).attr('a'),$(this).attr('b'),$(this).attr('c')
again and agin on every onclick just paas this object and get them all in function like :
onclick="triggersTracking(this,Enum.BtnSellerView)"
function triggersTracking(obj,enumVal){
// get these values here by obj (no repetitive code needed in every onclick )
$(obj).attr('a')
$(obj).attr('c')
$(obj).attr('b')
}
Do some thing like this
.click()
.on()
.data()
if you use attributes like data-enum , data-e....
so use $(this).data() it will return all attributes in JSON which is starting
from data-
$('.click').click(function(e) {
console.log($(this).data())
$('body').append($(this).attr('a'))
})
// if you have dynamic html tag then go for .on
$('body').on('click','.click',function(){
//callback
console.log($(this).data())
$('body').append($(this).attr('a'))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="click" a="i am a attr of p" b="i am b" data-a="i am data a">i am p</p>
<h2 class="click" a="i am a attr of h2">i am h2</h2>

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

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

Javascript: Dynamic Generation of a Div

I have several vertically stacks divs and I want to have a div appear when I click a button within each of these divs. The div that I want to appear will be the exact same for each appearance with the exception of an id associating it with the outer div. How do I do this in Javascript?
I assume I should use the createElement() within Javascript, but how do I append it to the end of a specific element. Also, when creating an element, I have to hardcode the html in the Javascript file. Is there anyway to leave the element within the html design file. I want to seperate design from code as much as possible.
Clone Node
var clone = myDiv.cloneNode();
Example (live demo):
HTML
<div>
<input type="button" onclick="functionClone(this);" value="Dolly"/>
<input type="button" onclick="functionClone(this);" value="Dolly_1"/>
</div>
Javascript:
functionClone = function(subject){
var clonenode = subject.cloneNode(true);
subject.value = subject.value + '\'s been cloned!';
subject.disabled = true;
insertElementAfter(subject, clonenode);
}
insertElementAfter = function(subject, newElement){
subject.parentNode.insertBefore(newElement,subject.nextSibling);
}
To append an element below your div use this:
subject.parentNode.appendChild(clonenode)

Categories

Resources