Here is what I am doing, I create a div structure dynamically
var divt = $('<div id="toplevel"></div>');
divt.append('<div id="child1"><div class="content1"></div></div>');
divt.append('<div id="child2"><div class="content1"></div></div>');
I then store a clone to a separate node and add it to the DOM.
this.emptydivt = $(divt).clone();
maindiv.append(divt);
Later on in my code I want to replace the contents of the top level DIV using one remove/append.
Firstly I create a new node from my previously saved...
this.newdivt = this.emptydivt.clone();
Here I want to get the child divs and append some new content , I have tried various function but can't get it to work eg.
var childdiv = this.newdivt.find('#child1').html();
childdiv.append('<div> new content</div>');
then after I will replace the top level div
maindiv.remove('#toplevel');
maindiv.append(this.newdivt);
So is there a way to get the child div from a Jquery or JS node that is not in the DOM ?
I see 2 typos in your code, not sure if on your real code they are not present
this.newdivt = this.emptydivt.clone(); // you missed ()
and
var childdiv = this.newdivt.find('#child1').html(); // you missed '' around #child1
Also, this code is not valid as clone doesn't accept a jQuery object as parameter
this.emptydivt = $(eventGrid).clone(divt);
Maybe you just want divt.clone()?
EDIT
Remove all white spaces on your elements ids as white spaces are not allowed on id attribute.
Related
I have a drop down which builds a form based of the selections that are selected. So, if someone selects 'foobar', it displays a text field, if they choose 'cheese', it displays radio buttons. The user can then enter data into these forms as they go along. The only problem is that when they add a new form element, all the rest of the information is erased. Im currently using the following to do add to the form:
document.getElementById('theform_div').innerHTML =
document.getElementById('theform_div').innerHTML + 'this is the new stuff';
How can I get it to keep whatever has be enetered in the form and also add the new field to the end?
Setting innerHTML destroys the contents of the element and rebuilds it from the HTML.
You need to build a separate DOM tree and add it by calling appendChild.
For example:
var container = document.createElement("div");
container.innerHTML = "...";
document.getElementById("theform_div").appendChild(container);
This is much easier to do using jQuery.
Step One:
Add jQuery to your headers:
<script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js”></script>
Step Two:
Append, don't replace, data to your DIV like this:
$("#theform_div").append("your_new_html_goes_here");
Don't use innerHTML to create the form elements. With innerHTML you're overwriting the old HTML with new HTML which will recreate all the elements. Instead you need to use the DOM to create and append the elements.
EXAMPLE
function addRadioElement()
{
var frm = document.getElementById("form_container");
var newEl = document.createElement("input");
newEl.type = "radio";
newEl.name = "foo";
newEl.value = "bar";
frm.appendChild(newEl);
}
The most correct way to do it without using a framework (like jQuery, Dojo, YUI) is:
var text = document.createTextNode('The text you want to write');
var div = document.createElement('div');
div.appendChild(text);
document.getElementById('theform_div').appendChild(div);
innerHTML, although supported by most browsers, is not standard compliant and - therefore, not guaranteed to work.
I would suggest using jQuery and its append function.
I'm adding custom toolbar elements to a Datatables table, but I am not sure how to add more than one.
I run the JS below and it moves one element into the toolbar:
var elementOne = $('#elementOne');
$("div.toolbar").html(elementOne);
How do I add a second element to the toolbar?
I tried adding just the html of each element:
var elementOne = $('#elementOne');
var elementTwo = $('#elementTwo');
$("div.toolbar").html(elementOne.html() + elementTwo.html());
But this resulted in duplicate elements and one of them (button) did not work properly. However, I could probably fix this but I'm wondering if there's a better way.
Also, I cannot generate one of the elements within JavaScript. It must be either moved, which I'd prefer, or copied.
I figured it out. I had to use the append JQuery method:
var elementOne = $('#elementOne');
var elementTwo = $('#elementTwo');
$("div.toolbar").append(elementOne);
$("div.toolbar").append(elementTwo);
I'm trying to add a search link to an online form with a userscript using jQuery. I don't work too much in firefox and I feel like things that would normally work in chrome don't in ff 9/10 times for me. But anyway... this needs to be with ff.
I'm taking the text from a <p> element and creating a search url out of it (or trying to). Right now this is the function I'm trying that should be doing it... but it's doing nothing, not even any errors in console
$(function() {
var companyName = $('p')[7]; // Element that contains the name text
var companyText = companyName.text(); // Retrieve the text from element
var mixRankUrl = $("<a></a>").innerHTML("Search Mixrank"); // Create an <a> element
mixRankUrl.href = 'https://mixrank.com/appstore/sdks?search=' + companyText; // Define the href of the a element
var sdkPara = $('label.control-label')[10]; // Where I want it to go
sdkPara.append(mixRankUrl); // Append the element
});
Also, whoever wrote the html uses hardly any ids, and most classes are assigned to 10 or more elements... so unless there's a better way, I'm sort of stuck using node selectors (which stay the same form to form).
The problem is that you try to use jQuery method on DOM element. Don't understand why you don't have any errors with your code.
For exemple : $('p')[7] return a DOM element while $('p').eq(7) return a JQuery object. So you can't use a jQuery method like text() on your DOM element. You need to deal with jQuery object.
For the same reason, you had a problem with the declaration of your label object and with the modification of the href attribute of your link.
Try like this :
$(function() {
var companyName = $('p').eq(7); // Element that contains the name text
var companyText = companyName.text(); // Retrieve the text from element
var sdkPara = $('label.control-label').eq(10); // Where I want it to go
var mixRankUrl = $('<a>',{
text: 'Search Mixrank',
href: 'https://mixrank.com/appstore/sdks?search=' + companyText
}).appendTo(sdkPara); // Append the element
});
I want to swap the content of two td's with each other by clicking on move up button.
I mean I want to swap content between the 2nd td and 3rd td.
I got that done but I am facing little problem in that i.e. "the swapped td's are not toggling the class that shows the current td is clicked or not after the swapping."
I am using this code for swapping the content of td's as below
var currentTr = $("#selectedTab td.backgroundcolor").parent();
var previousTr = currentTr.prev();
var temp = currentTr.html();
$(currentTr).html(previousTr.html());
$(previousTr).html(temp);
HTML manipulation in the DOM can be destructive. You should instead move the DOM nodes themselves.
var currentTr = $("#selectedTab td.backgroundcolor").parent();
var previousTr = currentTr.prev();
var temp = currentTr.contents().detach();
currentTr.append(previousTr.contents());
previousTr.append(temp);
This way you're not serializing, destroying and rebuilding all the nodes. You're just moving them.
Problem:
Extract all html between two headers including the headers html. The header text is known, but not the formatting, tag name, etc. They are not within the same parent and might (well, almost for sure) have sub children within it's own children).
To clarify: headers could be inside a <h1> or <div> or any other tag. They may also be surrounded by <b>, <i>, <font> or more <div> tags. The key is: the only text within the element is the header text.
The tools I have available are: C# 3.0 utilizing a WebBrowser control, or Jquery/Js.
I've taken the Jquery route, traversing the DOM, but I've ran into the issue of children and adding them appropriately. Here is the code so far:
function getAllBetween(firstEl,lastEl) {
var collection = new Array(); // Collection of Elements
var fefound =false;
$('body').find('*').each(function(){
var curEl = $(this);
if($(curEl).text() == firstEl)
fefound=true;
if($(curEl).text() == lastEl)
return false;
// need something to add children children
// otherwise we get <table></table><tbody></tbody><tr></tr> etc
if (fefound)
collection.push(curEl);
});
var div = document.createElement("DIV");
for (var i=0,len=collection.length;i<len;i++){
$(div).append(collection[i]);
}
return($(div).html());
}
Should I be continueing down this road? With some sort of recursive function checking/handling children, or would a whole new approach be better suited?
For the sake of testing, here is some sample markup:
<body>
<div>
<div>Start</div>
<table><tbody><tr><td>Oops</td></tr></tbody></table>
</div>
<div>
<div>End</div>
</div>
</body>
Any suggestions or thoughts are greatly appreciated!
My thought is a regex, something along the lines of
.*<(?<tag>.+)>Start</\1>(?<found_data>.+)<\1>End</\1>.*
should get you everything between the Start and end div tags.
Here's an idea:
$(function() {
// Get the parent div start is in:
var $elie = $("div:contains(Start)").eq(0), htmlArr = [];
// Push HTML of that div to the HTML array
htmlArr.push($('<div>').append( $elie.clone() ).html());
// Keep moving along and adding to array until we hit END
while($elie.find("div:contains(End)").length != 1) {
$elie = $elie.next();
htmlArr.push($('<div>').append( $elie.clone() ).html());
};
// htmlArr now has the HTML
// let's see what it is:
alert(htmlArr.join(""));
});
Try it out with this jsFiddle example
This takes the entire parent div that start is in. I'm not sure that's what you want though. The outerHTML is done by $('<div>').append( element.clone() ).html(), since outerHTML support is not cross browser yet. All the html is stored in an array, you could also just store the elements in the array.