Apply jquery to a code inserted with javascript - javascript

I have this line of code which is inserted via JS when the localDB is ready.
//
boxOne = document.getElementById("box1");
content = '<button data-icon="delete">Delete</button>';
boxOne.innerHTML = content;
//
The problem with this code is that mobilejquery should read data-icon="delete" and add the class's for the icon to appear but its not doing that.
I can simply add the class's manually by my self but this is also causing me trouble when I am trying to apply a validation library to a form that is inserted by JS the validation wont work.
So how can I make jquery & any library that I use Reads this inserted JS code.

I think you mean to put content inside boxOne. As it stands your trying to insert a DOM object (itself) into the innerHTML:
boxOne.innerHTML = content;
JSFiddle
Or, since it's available to you, just use jQuery:
$btn = $('<button/>',{text:'Delete','data-icon':'delete'});
$('#box1').html($btn);
JSFiddle

The other answers show you how to add the button, but not how to get jQuery Mobile to enhance it.
If you are using jQM 1.4, call enhanceWithin() on the container:
var content = '<button data-icon="delete">Delete</button>';
$("#box1").append(content).enhanceWithin();
If you are using 1.3, call button() on the button object:
var content = '<button data-icon="delete">Delete</button>';
$("#box1").append(content);
$("#box1 button").button();
NOTE: in my example I use append() to add the content, you can still use html() if you prefer.

With jQuery, you can use html():
$('#box1').html('<button data-icon="delete">Delete</button>');

Related

Add complexe Javascript array elements to HTML [duplicate]

I have a template:
function useIt() {
var content = document.querySelector('template').content;
// Update something in the template DOM.
var span = content.querySelector('span');
span.textContent = parseInt(span.textContent) + 1;
document.querySelector('#container').appendChild(
document.importNode(content, true));
}
<button onclick="useIt()">Use me</button>
<div id="container"></div>
<template>
<div>Template used: <span>0</span></div>
<script>alert('Thanks!')</script>
</template>
You can try the code here.
This code basically copies the template(html5 templates does not render on your screen) into another div. This allows you to reuse the DOM.
Problem: The line "span.textContent = parseInt(span.textContent) + 1;" changes the template code directly. I need to manipulate the content DOM and clone it into the container, without changing the template. This is very important since if I want to reuse the code, I need it to stay the same.
I have tried multiple ways to use jQuery to mimic the above javascript code, but I can't manage to figure it out. It would be better if there is a jQuery way.
If you NEED to use the new <template> tag, then you are mildly stuck . . . your cleanest alternative is to use importNode to bring in the content and then modify it after it's been appended.
Assuming that the templated code is realtively small, this should happen fast enough that you would never notice the difference in approach, though, in this specific example, the alert(), would delay the change of the content, so you would see "0", until you clicked "Okay", and then it would update to "1".
The code change for that would be:
function useIt() {
var content = document.querySelector('template').content;
var targetContainer = document.querySelector('#container');
targetContainer.appendChild(document.importNode(content, true));
var $span = $(targetContainer).find("div:last-of-type").find("span");
$span.text(parseInt($span.text() + 1));
}
If you are not married to the idea of <templates>, you could use jQuery's clone() method to do what you want to do, very easily . . . but, clone does not "see" the content of a <template>, due to the special nature of that particular element, so you would have to store the templated code some other way (JS variable, hidden div, etc.).
HOWEVER, this method will not work if you need to clone a script, the way that a <template> will. It will not trigger any script code in the "template container" element when the cloned version is created or appended. Additionally, if you store it in a hidden <div>, any script code in the "template container" element will trigger immediately on page load.
A simple version of the code for the clone() approach would look something like this:
function useIt() {
var $content = $("#template").clone();
var $span = $content.find("span");
$span.text(parseInt($span.text()) + 1);
$content.children().each(function() {
$("#container").append($(this));
});
}
Assuming that your template was:
<div id="template" style="display: none;">
<div>Template used: <span>0</span></div>
<script>alert('Thanks!')</script>
</div>
You could also move the <script>alert('Thanks!')</script> out of the template and into the script section (after you completed the "append loop"), to achive the desired alert functionality, if you wanted to.
It's an old question, but, did you try cloneNode(true)? It works on templates, as this:
var span = content.querySelector('span').cloneNode(true)
regards.

How to get html element after append with pure JavaScript?

I found some JQuery solutions, but I am limited by school task restrictions to use pure Javascript, and I need to use specific early appended element that is still not in DOM for replacing by my CKEDITOR.
Code:
function newOption(){
...
mainUL = document.getElementById("myUL");
var inputA = document.createElement("input");
inputA.type ="text";
inputA.style = "margin-right: 45px";
inputA.name = "option[]";
inputA.id = inputID;
mainUL.appendChild(inputA );
CKEDITOR.replace(inputID).setData('Type anything you want ...');
...
}
By replacing my input with CKEDITOR will JS fail, because input, commonly, is still not in DOM. I tried to use
mainUL.innerHTML += "all elements like html text";
and this is working and will immediately insert elements into DOM, but I can't to use innerHTML, because it will remove old listeners (for example checked checkboxes that JS will set from checked to unchecked, what is my main problem due to I have to try using append DOM function).
Try changing the code to wrap the call to CKEDITOR.replace in a setTimeout:
setTimeout(function() {
CKEDITOR.replace(inputID).setData('Type anything you want ...');
},0).
This will allow the browser time to insert the element before trying to replace it.
And I assume that inputID has a valid value in it...

Updating jQuery from 1.8 to 1.11 <a> tag not getting appended

I am trying to update this javascript code from 1.8 to 1.11, and I am having issues. The following code used to work in 1.8, but now it only half works (without errors).
I have the following function:
function selectCountry(c_id){
var obj = $('#country a[data-index=' + c_id + ']');
if(obj.hasClass('cselect'))
return;
var clone = obj.clone();
var div = $('<div class="keyword-box"></div>');
var remove = $('×');
clone.after(remove).appendTo(div);
div.prependTo('#selected_country');
obj.hide().addClass('cselect');
return false;
}
What it used to do is create a div like this:
<div class="keyword-box">
Albania
×
</div>
But now it is creating a div like this:
<div class="keyword-box">
Albania
</div>
I am not sure why the second a tag isn't getting added to the div any more. Can anyone see why this is happening?
There's been a change in jQuery at version 1.9
Prior to 1.9, .after(), .before(), and .replaceWith() would attempt to
add or change nodes in the current jQuery set if the first node in the
set was not connected to a document, and in those cases return a new
jQuery set rather than the original set. This created several
inconsistencies and outright bugs--the method might or might not
return a new result depending on its arguments! As of 1.9, these
methods always return the original unmodified set and attempting to
use .after(), .before(), or .replaceWith() on a node without a parent
has no effect--that is, neither the set or the nodes it contains are
changed.
In your case you can just change
clone.after(remove).appendTo(div);
to
clone.add(remove).appendTo(div);
or
div.append(clone, remove);
I think your code would be much more readable if you would add the links like this:
div.append(clone);
div.append(remove);
div.prependTo('#selected_country');
The .after() API changed in jQuery 1.9. Using it in your case now has no effect. I think you should probably create the <div> and explicitly append both <a> elements individually to it.
So:
var div = $('<div class="keyword-box"></div>');
var remove = $('×');
remove.appendTo(div);
clone.appendTo(div);

Finding $(this) after a function

So here's my problem: I'm using a function and I need the function to be specific to each tr with the class "middleone". It's supposed to change the insides of a div inside of the the tr with the class "middleone". But it's not working!
I know the recursive portion of it is working, and the "navigation" should be spot on, because even when i'm using just $(this) it doesn't do anything. When using document.getElementById it works fine but of course that only targets the first div and the full version of the code has to "Go here, pull from here, put it here, go to the next area, pull from here.. etc" Here's the testing code.
$('.middleone').each(function() {
var tripleeagain = $(this).find('div')
tripleeagain.innerHTML = "$";
});
Thanks for any help
tripleeagain is a jquery object collection upon which you should use html() instead of innerHTML
Basically you could just write:
$('.middleone').find('div').html("$");
If you are doing specific stuff inside the loop then:
$('.middleone').each(function() {
//Some specific logic
var tripleeagain = $(this).find('div').html("$");
});
The problem is you are trying to access native API from a jQuery object.
var tripleeagain = $(this).find('div');// this will return a jQuery object
So you should use the jQuery API for setting the html contents
tripleeagain.html("$");
jQuery html API documentaion

Javascript - clearing everything inside a div

I have div:
<div id="socialUserList">
//some content here, htmlTags, text, etc.
</div>
Now, I want everything inside of that div to be wiped out. I am trying this:
$("#socialUserList").innerHTML = '';
But for some reason it doesn't want to work. Why?
The normal JavaScript method:
document.getElementById('socialUserList').innerHTML = '';
In jQuery:
$('#socialUserList').html('');
Pure JavaScript and jQuery go hand in hand, like so:
From pure JavaScript to jQuery:
var socialUserList = document.getElementById('socialUserList');
console.log($(socialUserList).html());
From jQuery to pure JavaScript:
var socialUserList = $('#socialUserList');
console.log(socialUserList[0].innerHTML);
Have you tried:
jQuery('#socialUserList').empty();
Note: You may have also tried this:
jQuery('#socialUserList')[0].innerHTML = '';
Using the [0] will access the DOM object of the first matching element.

Categories