Convert a string of HTML into DOM objects with jQuery - javascript

I have HTML in a JavaScript string (containing usual, nested HTML). Using jQuery, can I convert that into a valid HTML element in a single stroke using any of the document.create* functions? My requirement is to use document.getElementById on the created DOM object.

Take simple nested example.
var dom_string = '<div>xxx<div>yyy</div></div>';
create HTML DOM elements using $() function of jquery and append wherever you want.
i have taken 'body' but you can append anywhere.
$(dom_string).appendTo('body');
Alternatively you can implement this with pure javascript:
var dom_target = document.getElementById("target");
dom_target.innerHTML = dom_string;

Create a dummy element and set its innerHTML to your HTML string.

// Construct a container as a placeholder for your content
var container = document.createElement('div');
container.id = 'container';
// Inject the container into the DOM
document.body.appendChild(container);
// Populate the injected container with your content
container.innerHtml = '<p id="pTag">I am a <em>P</em> tag with some <strong>nested markup</strong>.</p>';

To convert Html text into a Jquery-Object use the $() function:
div = '<div>hello world</div>';
$div = $(div);
But as others have noted in most cases you don't need that because DOM manipulation functions like append() and prepend() will accept plain text, so
$('body').append('<div>hello world</div>');
is absolutely fine.

Related

Append values to a specific element in a string with Jquery

I have an element in local storage with multiple elements, for simplicity, I will make the element:
<div id="outer">
<ul id="inner">
<li id="item">
</li>
</ul>
</div>
The element is saved as a string and I want to manipulate the contents.
Like such:
let local_storage_element = localStorage.getItem("val")
$(local_storage_element+':last-child').append("<p>something</p>")
No matter what selector I add after local_storage_element it will always append the value to the string not to the selected element(:last-child in this case)
does anyone know how to append to a specific element within the string??
Although you have written jquery in the title there is a javascript tag added also so I thought why not provide an answer that justifies your needs and helps you accomplish the task in the same way you want.
The
DocumentFragment interface represents a minimal document object that has no parent. It
is used as a lightweight version of Document that stores a segment of
a document structure comprised of nodes just like a standard document.
The key difference is that because the document fragment isn't part of
the active document tree structure, changes made to the fragment don't
affect the document, cause reflow, or incur any performance impact
that can occur when changes are made.
So how to do it as the DocumentFragment still appends node with it and not string, we will create a temp element and add the HTML from the localStorage using innerHtml and then append the firstChild of that temp node i.e our actual string which is now treated as a node, to the document fragment and then search and appends HTML to it, we will use our temp element to add HTML every time see below.
I will append a new child div to the element #outer in the string given above in the post here is the working FIDDLE as SO does not support localStorage you can see it working there open the console to view the resulting HTML with the new child added and below is the code
$(document).ready(function () {
if (localStorage.getItem('html') === null) {
localStorage.setItem('html', '<div id="outer"><ul id="inner"><li id="item"></i></ul></div>');
}
var frag = document.createDocumentFragment();
var temp = document.createElement('div');
temp.innerHTML = localStorage.getItem('html');
frag.appendChild(temp.firstChild);
temp.innerHTML = '<div class="new-child"></div>'
frag.querySelector("#outer").appendChild(temp.firstChild);
console.log(frag.querySelector("#outer"));
localStorage.removeItem('html');
});
You can't use string as selector. If you want transform string to html then you should put it in some element as innerHTML. So try create some hidden div and insert your string as HTML to it. Something like this
var your_string = '<ul><li>1</li><li>2</li><li>3</li><li>4</li></ul>';
document.querySelector('.hidden').innerHTML = your_string;
document.querySelector('ul li:last-child').innerHTML = 'your content';
document.querySelector('.result').appendChild(document.querySelector('ul'));
Example
The problem may arise when you get '<div id="outer">' from localStorage to use it as a selector since it only accepts "#outer" to be a selector. If you want to add an element to be the last child of parent's element, you could use after() instead of append().
$(document).ready(() => {
if ($("#charl").children().length === 0)
{
// if using after with no element inside ul then it will be inserted after il
$("#charl").html("<li>foo</li>")
}
else {
$("#charl li").after("<li>bar</li>")
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="charl">
<li>Foo</li>
</ul>

Storing data in html dynamically (html5)

I am creating a dynamic div in html which consists of multiple checkboxes. All these checkboxes and divs are being dynamically added to the html. I need to store some data about each div in the html to be accessed by javascript later. Can anyone show me an example where data can be added and retrieved dynamically in a div? I know HTML5 allows it and there are some other hacks to do it, but I am having trouble with syntax I guess.
Try to do it using JavaScript:
SomeClass.someVariable = document.getElementById('divid');
Otherwise if you mean to access custom data that has to used as attribute in your HTML tags then use
data-XXX = 'YYY';
And access it with JS:
document.getElementById('divid').dataset.XXX;
This post explains data-* attributes.
You can create custom attributes within your divs like this:
<div id="div1" data-text="Hello. This is a custom attribute."></div>
Notice the data- prefix. this is absolutely necessary.
Then (using jQuery) you can access the custom attribute:
$('#div1').data('text'); => "Hello. This is a custom attribute."
So using this you can do stuff like:
if($('#div1').data('text') != "FreddieBobman"){
alert("HI!");
} else {
alert("Forever Alone!");
}
The above example will alert "HI!" because $('#div1').data('text') does not contain
FreddieBobman, it is in fact "Hello. This is a custom attribute."
To create these attributes use the following:
$('#div1').attr('data-name', 'value');
Our div with id of div1 now has another attribute, data-name, and the attribute has a value of value. Of course, you can change the value of attributes as well:
<div id="div1" data-text="Hello. This is a custom attribute."></div>
<script src="jquery.js"></script>
<script>
(function(){
$('#div1').attr('data-text', 'This is cool.');
}());
</script>
Now the div has data-text equal to "This is cool.", not "Hello. This is a custom attribute."
It is Obtain by the data attributes that you add dynamically to the elements ,And retrieve when you want !
SET Attribute :
var div = document.createElement('div');
div.setAttribute('data','my_data');
div.innerHTML = "I am a div";
document.body.appendChild(div);
GET Attribute :
div.getAttribute('data')
WORKING DEMO
you can use attributes for your html tags. Also, in html5 you can also use custom attributes
What you want is to add or retrieve data from div tags dynamically?
Using javascript function you can simply get corresponding div element using its id,
var container = document.getElementById('your_element_id');
Then you can add what you want.
var stringToAdd = "<p>something you want to add</p>";
container.innerHTML = stringToAdd;
Also you can use a different class with different features and set it as your div class.
you need to add your features inside style tag under your class name. Then,
var elementID = document.getElementById(ID);
elementID.className ="your_new_class_name";
or you can set attributes for your tag.
elementID.setAttribute('display','inline');
Using jquery with javascript,
var elementID = document.getElementById(ID);
$(elementID).replaceWith( "<p>something you want to replace</p>" );
using class name or id you can dynamically append content using,
var stringToAdd = "<p>something you want to add</p>";
$(".your_class_name").append(stringToAdd);
also you can remove whole element using,
$(elementID).remove();

How to duplicate a div in JavaScript

I was wondering how I can duplicate a DIV element a few times through JavaScript without duplicating the DIV in my html code?
Let's assume the you selected the div doing something like:
var myDiv = document.getElementById("myDivId");
The DOM API contains a cloneNode method which you can use
var divClone = myDiv.cloneNode(true); // the true is for deep cloning
Now you can add it to the document
document.body.appendChild(divClone);
Here is a short self contained code example illustrating this

Jquery get image HTML

How can I copy the whole <img /> using jquery.
At the moment I am trying: $('img').clone().html()
Usage:
'<div class="content-left">'+$(this).find(".bar .info").html()+$(this).find(".bar img").clone().html()+'</div>';
To create new copies of every image in the DOM you can select them and clone them, then append them to some container.
//store a clone of all the images in the DOM in a variable
var $clone = $('img').clone();
//now add the clones to the DOM
$('#newContainer').html($clone);
Here is a demo: http://jsfiddle.net/jasper/r3RDx/1/
Update
You can create your HTML like this:
//create a new element to add to the DOM
//start by creating a `<div>` element with the `.content-left` class
//then add a string of HTML to this element
//then append a set of DOM elements (clones) to the same parent element (the `<div>`)
var $newElement = $('<div />').addClass('content-left').html($(this).find('.bar .info').html()).append($(this).find('.bar img').clone());
//then you can add the new element(s) to the DOM
$newElement.appendTo('#newContainer');
Here is a demo: http://jsfiddle.net/jasper/r3RDx/2/
jQuery objects are simple arrays containing the html of the selected element. This means that I can simply do: $('img.someclass')[0] to access the html of the first (and probably only) matched element.
clone includes the event handlers of the object. If you want just the html whats below would be fine
$('#someid').html($('img'))

How to use jQuery selector/find() against text string without inserting into the DOM?

I have a text string i'm trying to select the spans from using jQuery. I'd like to grab the spans w/o adding the element to the dom -- if that's possible?
After reading the jquery docs i was under the assumption that i could create a fragment by wrapping the string in a jquery selector tag, then using.find() to find the elements i want.
I have code that is similar to this but from the looks of the last line, it's obvious that no spans are being selected; any help would be greatly appreciated:
// 'text' is normally generated automatically...
// just made it an escaped string for example purposes.
var text ="<span id=\"blah1\">Y</span><br/><span id=\"blah2\">o</span><br/>";
var spans = $(text).find('span');
console.log(text); // => <span id="blah1">Y</span><br/><span id="blah2">o</span><br/>
console.log(spans.length); // => 0
Thanks.
You want to use filter(), not find()
var text ="<span id=\"blah1\">Y</span><br/><span id=\"blah2\">o</span><br/>";
var spans = $(text).filter('span');
console.log(spans.length);
jsFiddle
From the jQuery docs
filter:
The supplied selector is tested against each element; all elements
matching the selector will be included in the result.
find:
the .find() method allows us to search through the descendants of
these elements in the DOM tree and construct a new jQuery object from
the matching elements.
with your html fragment, there is no wrapper element, so there is no descendants, hence why find() does not work.
You are basically doing:
var elems = jQuery("<span id=\"blah1\">Y</span>").add("<br/>").add("<span id=\"blah2\">o</span>").add("<br/>");
If you want find to work with find(), you need to wrap it in an element.
var text ="<span id=\"blah1\">Y</span><br/><span id=\"blah2\">o</span><br/>";
var spans = jQuery("<div></div>").append(text).find("span");
console.log(spans.length);
You want to use filter in this case:
var text ="<span id=\"blah1\">Y</span><br/><span id=\"blah2\">o</span><br/>";
var spans = $(text).filter('span');
console.log(spans.length); // 2
Demo: http://jsfiddle.net/ambiguous/TGY3J/
Or wrap it in a <div> and use find:
var text ="<span id=\"blah1\">Y</span><br/><span id=\"blah2\">o</span><br/>";
var spans = $('<div>' + text + '</div>').find('span');
console.log(spans.length); // 2
Demo: http://jsfiddle.net/ambiguous/qbCjk/
find works on descendants but without the <div> wrapper, your $(text) doesn't have any <span> descendants. Wrapping your HTML in a <div> is probably your best bet, that way you don't have to worry about how deep your desired elements are.

Categories