Error in jQuery showing id undefined - javascript

I have a jQuery script which creates div in this fashion
function dump_template(src,close_div)
{
var item_template = $('<img/>', {'id':'target','src':src});
var first_text = $('<div/>', {'id':'first_text','class':'edit_text'});
$(first_text).css({"left":"0px",
"top":"0px",
"color":"#fff",
"position":"relative",
"width":"auto",
"text-align":"center"});
$(first_text).html('Demo First Text');
var second_text = $('<div/>', {'id':'second_text','class':'edit_text'});
$(second_text).css({"left":"0px",
"top":"0px",
"color":"#fff",
"position":"relative",
"width":"auto",
"text-align":"center"});
$(second_text).html('Demo Second Text');
$('#main_canvas').html(item_template);
var width = $("#target").width();
var height = $("#target").height();;
$('#main_canvas').css({'height':height+'px','width':width+'px'});
var drag_first_text = $('<div/>', {'id':'drag_first_text','class':'context-menu-text'});
var drag_second_text = $('<div/>', {'id':'drag_second_text','class':'context-menu-text'});
$(drag_first_text).css({"left":"20px",
"top":"100px",
"position":"absolute",
"width":"auto",
"z-index":"5",
"text-align":"center",
});
$(drag_second_text).css({"left":"20px",
"top":"150px",
"position":"absolute",
"width":"auto",
"z-index":"5",
"text-align":"center"});
$(drag_first_text).append(first_text);
$(drag_second_text).append(second_text);
$('#main_canvas').append(drag_first_text).append(drag_second_text);
$(drag_first_text).draggable({grid:[1,1]});
$(drag_second_text).draggable({grid:[1,1]});
HideModalPopup(close_div);
}
Now I have some code in jQuery like this:
var content = $(this).find('.edit_text').text();
var outside_div_id = $(this).id;
alert(outside_div_id);
var inside_div_id = $(this).find('.edit_text').id;
alert(inside_div_id);
Here in the above example of code, $(this) refers to the div with ids "drag_first_text" and "drag_second_text" corresponding to the selected div.
But alert(outside_div_id); and alert(inside_div_id); both gives me undefined.
How can I find the glitch?

You either need to convert that to native Element using get or using index or use attr("id")
var outside_div_id = $(this)[0].id; // or $(this).attr("id")
alert(outside_div_id);

There is no such thing as .id.
var outside_div_id = $(this).attr('id');
alert(outside_div_id);
var inside_div_id = $(this).find('.edit_text').attr('id');
alert(inside_div_id);
Let me know if you have any question.

Related

How can I clone element and append to the clone another el?

I have some id div with elements(classes and Ids), I need to clone it and append to my clone new class. How can I do it?
window.onload = Func ();
function Func () {
var temp = document.getElementById("start");
var cl = temp.cloneNode(true);
var div = document.createElement('div');
div.className = "class";
div.innerHTML = "MyText";
var result = cl.getElementById("second").append(div);
alert(result.innerHTML);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="start">
<div id="second">
Link
</div></div>
use following code
$(function(){
var $Div = $('.start').clone();
$('.second').html($Div);
});
Using JQuery,
var clone = $("#divName");
or var clone = $(".className")
var secondDiv = $("#secondDiv");
or var secondDiv = $(".secondDivClassName");
//Or you can get the html of your second div like this:
var myHtml = secondDiv.html(); //if you don't give any parameter, it takes the inner html of the given element.
//and finally insert your html into the clone like this :
clone.html(myHtml);// in this case, the html() methode takes a parameter and inserts the given parameters into the given element.
You should reference JQuery to your page.
Tell me if it works.

How can I add dynamic created elements to my dynamic created list?

I'm having some issues adding dynamic created list items to dynamic created list. I've created a function that returns dynamically created ul and li.
From here I create two lists:
var el = Part.mainSearchResult();
var brandList = $(el.ul).clone(true);
var storeList = $(el.ul).clone(true);
Q1. Should I use .clone() here?
Then I try to add the list elements to the list, and output this. But I'm not that successfullt.
Q2. What am I doing wrong when applying list elements to list?
You can see my fiddle here.
var Part = {
mainSearchResult : function(){
var el = {}
el.ul = $("<ul />", {
'data-role': "listview",
'data-inset' : "true"
});
el.brand = $("<li />", { 'data-role': "listview", 'data-inset' : "true"})
.append($("<a />", { 'href': "#"}));
el.store = $('<li/>', {'data-role': "listview", 'data-inset' : "true"}).append(
$('<a/>', {'href': '#'}).append(
$('<div/>', {'class': "name"})
).append(
$('<div/>', {'class': "location"})
)
);
return el;
}
};
function test(response) {
var el = Part.mainSearchResult();
var brandList = $(el.ul).clone(true);
var storeList = $(el.ul).clone(true);
$(response.brands).each(function(){
var brand = $(this)[0];
var url = 'http://www.jsfiddle.com/' + brand.name + '/' + brand.id;
var li = el.brand[0]; // Maybe I should clone this?
$(li).find('a').prop('href',url);
$(li).find('a').text(brand.name);
brandList.append(li);
});
$('.result').append(brandList);
console.log(brandList);
}
You put the html in the css pane :D
<div class="result"></div>
http://jsfiddle.net/etsg4vvw/4/

Clone <div> and change id

How can I using javascript make clone of some <div> and set his id different from original. Jquery also will be nice.
var div = document.getElementById('div_id'),
clone = div.cloneNode(true); // true means clone all childNodes and all event handlers
clone.id = "some_id";
document.body.appendChild(clone);
Use it:
JQuery
var clonedDiv = $('#yourDivId').clone();
clonedDiv.attr("id", "newId");
$('#yourDivId').after(cloneDiv);
I had the same problem. I've solved that by setting a counter and appending it to the ID. Hope it helps you too:
<script type="text/javascript">
var counter = 1; //Set counter
function clone(sender, eventArgs) {
var $row = $('#yourID');
var $clone = $row.clone(); //Making the clone
counter++; // +1 counter
//Change the id of the cloned elements, append the counter onto the ID
$clone.find('[id]').each(function () { this.id += counter });
}
</script>
jQuery have method clone()
var original = $("#original");
var newClone = original.clone();

Can you use appendChild to add an element to a div that had a dynamically created id?

I am trying to add some <p> elements to a div using Javascript. The function loops to create a predetermined amount of these divs. My id for the div is created every time the function runs, and is just 'div' plus a number (e.g.: div1, div2, div3, etc.)
Here is my code:
var divNum = 'div';
function myFunction () {
var divTag = document.createElement("div");
divTag.id = "div";
divTag.className ="info";
document.body.appendChild(divTag);
var idXX = divNum;
$('#div').attr('id',idXX);
var text = document.createElement("p");
text.id = "1";
text.className ="text1-2";
text.innerHTML = "A";
*"PROBLEM HERE"*.appendChild(text);
divNum = divNum + 1;
}
My question is, can you do something to where it says *"PROBLEM HERE"* that makes it append a div with id equal to my var idXX?
Just use divTag.
That line would look like this:
divTag.appendChild(text);
I may be misunderstanding the question, but it seems to me that the "PROBLEM HERE" line should just be this:
$('#'+idXX).append(text); // literally doing what you asked
Or simply this:
divTag.appendChild(text); // better approach since it doesn't have to go look for it.
Also, why do you create the div and then change its ID? Also, divNum is initialized as "div", not 0 like is presumably intended...
If you want to use jQuery and not mix it with base javascript:
var divNum = 'div';
function myFunction () {
var divTag = $("<div>").
.attr("id", divNum)
.addClass("info");
.appendTo($("body"));
$("<p>")
.attr("id", "1")
.addClass("test1-2")
.html("A")
.appendTo(divTag);
divNum = divNum + 1;
}
Looks like your using jQuery to set the attribute id.
$('#div').attr('id',idXX);
You should be able to do everything in jQuery
var divNum = 0;
function myFunction() {
var _p = $('<p>').text('A').addClass('text-1-2')
$('<div>').attr({'id':'div'.concat(++divNum)}).addClass('info').html(_p).appendTo('body');
}

jQuery/javascript replace tag type

Is there an easy way to loop through all td tags and change them to th? (etc).
My current approach would be to wrap them with the th and then remove the td, but then I lose other properties etc.
jQuery.replaceTagName
The following is a jQuery plugin to replace the tag name of DOM elements.
Source
(function($) {
$.fn.replaceTagName = function(replaceWith) {
var tags = [],
i = this.length;
while (i--) {
var newElement = document.createElement(replaceWith),
thisi = this[i],
thisia = thisi.attributes;
for (var a = thisia.length - 1; a >= 0; a--) {
var attrib = thisia[a];
newElement.setAttribute(attrib.name, attrib.value);
};
newElement.innerHTML = thisi.innerHTML;
$(thisi).after(newElement).remove();
tags[i] = newElement;
}
return $(tags);
};
})(window.jQuery);
Minified Source
(function(e){e.fn.replaceTagName=function(t){var n=[],r=this.length;while(r--){var i=document.createElement(t),s=this[r],o=s.attributes;for(var u=o.length-1;u>=0;u--){var a=o[u];i.setAttribute(a.name,a.value)}i.innerHTML=s.innerHTML;e(s).after(i).remove();n[r]=i}return e(n)}})(window.jQuery);
Usage
Include the above minified source in your javascript after jQuery.
Then you can use the plugin like this:
$('div').replaceTagName('span'); // replace all divs with spans
Or in your case this:
$('td').replaceTagName('th');
jQuery selectors work as expected
$('.replace_us').replaceTagName('span'); // replace all elements with "replace_us" class with spans
$('#replace_me').replaceTagName('div'); // replace the element with the id "replace_me"
More resources
jsFiddle with Qunit tests
Completely untested, but giving this a whirl:
$("td").each(function(index) {
var thisTD = this;
var newElement = $("<th></th>");
$.each(this.attributes, function(index) {
$(newElement).attr(thisTD.attributes[index].name, thisTD.attributes[index].value);
});
$(this).after(newElement).remove();
});
I'm looking and looking at it, and I can't think of a reason why it wouldn't work!
1) loop through each td element
2) create a new th element
3) for each of those td's, loop over each of its attributes
4) add that attribute and value to the new th element
5) once all attributes are in place, add the element to the DOM right after the td, and remove the td
Edit: works fine: http://jsbin.com/uqofu3/edit
$("td").each(function() {
var tmp = $('<div/>').append($(this).clone(true)).html().replace(/td/i,'th');
$(this).after(tmp).remove();
});
or pure DOM
function replaceElm(oldTagName, newTagName, targetElm) {
var target = targetElm || window.document;
var allFound = target.getElementsByTagName(oldTagName);
for (var i=0; i<allFound.length; i++) {
var tmp = document.createElement(newTagName);
for (var k=0; k<allFound[i].attributes.length; k++) {
var name = allFound[i].attributes[k].name;
var val = allFound[i].attributes[k].value;
tmp.setAttribute(name,val);
}
tmp.innerHTML = allFound[i].innerHTML;
allFound[i].parentNode.insertBefore(tmp, allFound[i]);
allFound[i].parentNode.removeChild(allFound[i]);
}
}
replaceElm('td','th',document.getElementsByTagName('table')[0]);
DOM is always faster: http://jsperf.com/replace-tag-names
This might work, but I haven't tested it extensively:
var tds = document.getElementsByTagName("td");
while(tds[0]){
var t = document.createElement("th");
var a = tds[0].attributes;
for(var i=0;i<a.length;i++) t.setAttribute(a[i].nodeName,a[i].nodeValue);
t.innerHTML = tds[0].innerHTML;
tds[0].parentNode.insertBefore(t,tds[0]);
tds[0].parentNode.removeChild(tds[0]);
}
I hope it helps in some way.
Slight addition to #GlenCrawford answer, to also preserve inner text with the line:
newElement.text($(value).text());
All together now:
$("td").each(function(index) {
var thisTD = this;
var newElement = $("<th></th>");
newElement.text($(value).text());
$.each(this.attributes, function(index) {
$(newElement).attr(thisTD.attributes[index].name, thisTD.attributes[index].value);
});
$(this).after(newElement).remove();
});
Well this question is pretty old but this could help anyway: the only jQuery plugin that actually works as expected (you can't reuse the returned object in the other one, to add attributes for example):
jQuery.fn.extend({
replaceTagName: function(replaceWith) {
var tags=[];
this.each(function(i,oldTag) {
var $oldTag=$(oldTag);
var $newTag=$($("<div />").append($oldTag.clone(true)).html().replace(new RegExp("^<"+$oldTag.prop("tagName"),"i"),"<"+replaceWith));
$oldTag.after($newTag).remove();
tags.push($newTag.get(0));
});
return $(tags);
}
});
Besides the basic $("td").replaceTagName("th"); you can also chain calls like $("td").replaceTagName("th").attr("title","test");
Minified version:
jQuery.fn.extend({replaceTagName:function(a){var b=[];this.each(function(d,c){var e=$(c);var f=$($("<div />").append(e.clone(true)).html().replace(new RegExp("^<"+e.prop("tagName"),"i"),"<"+a));e.after(f).remove();b.push(f.get(0))});return $(b)}});
This is a bit cleaner than #GlenCrawford's answer and additionally copies the children of the replaced element.
$('td').each(function(){
var newElem = $('<th></th>', {html: $(this).html()});
$.each(this.attributes, function() {
newElem.attr(this.name, this.value);
});
$(this).replaceWith(newElem);
});

Categories

Resources