I am using jQuery and everything works fine except a few stuff. There are a few things you cannot do with the jQuery format of an element but only with the simple JS format. Especially, when using the hasAttributes() in simple JS.
This works:
let fooDiv = document.getElementsByTagName("div")[0];
console.log(fooDiv.hasAttributes()); //returns false as expected
let barDiv = document.getElementsByTagName("div")[1];
console.log(barDiv.hasAttributes()); //returns true as expected
<div>foo</div>
<div id="id">bar</div>
This doesn't:
let fooDiv = $(document.getElementsByTagName("div")[0]) //creates a jQ object
console.log(fooDiv.hasAttributes()); //error
let barDiv = $(document.getElementsByTagName("div")[1]) //creates a jQ object
console.log(barDiv.hasAttributes()); //error
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>foo</div>
<div id="id">bar</div>
I am aware that the jQuery hasAttr() exists but I want to get the JS format of a jQuery object. There are a lot of differences, for example the jQuery creates an object but otherwise it is a html node list.
Initially, my question is:
How do I get the html node list or html element or the simple JS format of a html element(s) from jQuery?
To expand on what blex said in the comments ... when jQuery is used to select an HTML element, the raw HTML is always collected in an array as part of the variable you assign it to. For example, using your code:
// grab the element or elements
let fooDiv = $(document.getElementsByTagName("div")[0]);
// lets see the HTML!
consoe.log( fooDiv[0] );
The HTML itself will be exposed in that array, allowing direct access to the HTML and its properties... for example:
console.log( fooDiv[0].innerHTML );
or
console.log( fooDiv[0].tagName );
Related
I am working on a website that shows different APIs we provide. It showcases the example code and preview for each API and a button to open code in plunker. Since we have 100s of examples, we are not creating plunker for every example, but opening a new tab "https://plnkr.co/edit/?p=preview" and appending the corresponding html code into it.
Problem:
I have a total HTML document as a string in a javascript variable.
var html = "`<DOCTYPE html><html>....<body><script>abc.loader.load({apiToken:'', name:'',...});</script></body>`"
I have to change the object inside abc.loader.load(). Is there any way I can pick up the object inside abc.loader.load() and make changes in javascript and replace with existing object.
You can use a template literal and inject ${JSON.stringify(obj)} into that, like this:
<!--
var obj = {apiToken:'', name:''};
var html = `<!DOCTYPE html><html>....<body>
<script>abc.loader.load(${JSON.stringify(obj)});</script></body></html>`;
console.log(html);
-->
The script content is wrapped in <!-- --> to avoid misinterpretation of < inside your string.
Reading out the object and writing it again after mutation:
Although I would try to stick to the above template string, and would repeat the injection of different objects into it, here is what you could do when you have a given HTML string, and need to extract the object. This only works if the object literal is JSON compliant, i.e. it double quotes strings, and also property names:
<!--
var html = `<!DOCTYPE html><html>....<body>
<script>abc.loader.load({"apiToken":"", "name":""});</script></body></html>`;
html = html.replace(/(loader\.load\()(.*?)(?=\);<\/script>)/, function (_, prefix, json) {
var obj = JSON.parse(json); // get the object
obj.test = 3; // modify the object as you wish
return prefix + JSON.stringify(obj); // put the object
});
console.log(html);
-->
I have a big HTML-string containing multiple child-nodes.
Is it possible to construct a jQuery DOM object using this string?
I've tried $(string) but it only returns an array containing all the individual nodes.
Imtrying to get an element which i can use the .find() function on.
Update:
From jQuery 1.8, we can use $.parseHTML, which will parse the HTML string to an array of DOM nodes. eg:
var dom_nodes = $($.parseHTML('<div><input type="text" value="val" /></div>'));
alert( dom_nodes.find('input').val() );
DEMO
var string = '<div><input type="text" value="val" /></div>';
$('<div/>').html(string).contents();
DEMO
What's happening in this code:
$('<div/>') is a fake <div> that does not exist in the DOM
$('<div/>').html(string) appends string within that fake <div> as children
.contents() retrieves the children of that fake <div> as a jQuery object
If you want to make .find() work then try this:
var string = '<div><input type="text" value="val" /></div>',
object = $('<div/>').html(string).contents();
alert( object.find('input').val() );
DEMO
As of jQuery 1.8 you can just use parseHtml to create your jQuery object:
var myString = "<div>Some stuff<div>Some more stuff<span id='theAnswer'>The stuff I am looking for</span></div></div>";
var $jQueryObject = $($.parseHTML(myString));
I've created a JSFidle that demonstrates this: http://jsfiddle.net/MCSyr/2/
It parses the arbitrary HTML string into a jQuery object, and uses find to display the result in a div.
var jQueryObject = $('<div></div>').html( string ).children();
This creates a dummy jQuery object in which you can put the string as HTML. Then, you get the children only.
There is also a great library called cheerio designed specifically for this.
Fast, flexible, and lean implementation of core jQuery designed specifically for the server.
var cheerio = require('cheerio'),
$ = cheerio.load('<h2 class="title">Hello world</h2>');
$('h2.title').text('Hello there!');
$('h2').addClass('welcome');
$.html();
//=> <h2 class="title welcome">Hello there!</h2>
I use the following for my HTML templates:
$(".main").empty();
var _template = '<p id="myelement">Your HTML Code</p>';
var template = $.parseHTML(_template);
var final = $(template).find("#myelement");
$(".main").append(final.html());
Note: Assuming if you are using jQuery
the reason why $(string) is not working is because jquery is not finding html content between $(). Therefore you need to first parse it to html.
once you have a variable in which you have parsed the html. you can then use $(string) and use all functions available on the object
You can try something like below
$($.parseHTML(<<table html string variable here>>)).find("td:contains('<<some text to find>>')").first().prev().text();
I know this is an old thread, but I have another simple answer. jQuery has moved up quite a few versions and I'm on 1.13.x
Not being an expert jQuery programmer, I näively used:
var el = $( "#thecontainer" ).append( "<legit, lengthy html>" );
And presto! It worked: el is now a fully operational jQuery dom element.
I have been testing it out over the past couple of days and it seems to work as expected.
in an XML node that looks like this:
why would this code not work?
xml = $.parseXML( xml );
console.log(xml);
plot = $(xml).find("movie");
aP = plot.attributes
console.log(aP);
I am getting undefined for console log. aP
i also tried aP = $(plot).attributes
attributes is not a jquery property. Try plot.get(0).attributes this way you can use the attributes property on your element and not on a jquery object.
$(xml).find("movie"); //returns jquery object
$(plot) // is a jquery object of a jquery object. You really want your object to be a jquery object aye?
get(index): Description: Retrieve one of the elements matched by the
jQuery object.
In other words, your get returns an actual element.
var board_code_clone = $('#board_code').contents().clone(false);
alert( board_code_clone.filter('div').eq(x).children().eq(y).text() );//make this right
i want to have a code equivalent to this
$('#board_code_dup > div').eq(x).children().eq(y).text();
My intention for this is to have a clone copy of the code they type on #board_code and then i will be trying to manipulate it using board_code_clone and then append the manipulated board_code_clone to the html dom
If I'm understanding correctly, you can just do your clone, make the modifications and then append back to the DOM, just as you said:
// Get the contents
var clone = $('#board_code').contents().clone(false);
// Do your manipulations
var edited = // modify `clone` as necessary
// Append back to the DOM
$('#new_content').append(edited);
I am trying to parse some elements of a form.
I have with me the form ID/form name.
Now I want to parse through all radio buttons with name= "radio123"(or id="radio123").
But when I try $(this).html on each element (of a radio button)... then I get a blank value...
How do I access the HTML code for all radiobuttons/checkboxes within a form?
This is the normal behavior for jQuery.fn.html function: This method uses the browser's innerHTML property. Look at the examples if you don't understand what I mean.
I don't know why you want to get the HTML (if you want the value, look at the jQuery.fn.val method), but here's a solution
$("input:radio").each(function () {
console.log( this.outerHTML );
});
Be careful with the outerHTML, as it is not supported across all browsers you could use this function:
function getOuterHTML( node ) {
var parent = node.parentNode,
el = document.createElement( parent.tagName ),
shtml;
el.appendChild( node );
shtml = el.innerHTML;
parent.appendChild( node );
return shtml;
}
// use it like getOuterHTML( this ) in the preceding each loop
Something like this should work -
var htmlarr = [];
$("input[type='radio'][name='radio123'],[type='radio'][id='radio123']").each(function () {
//any logic you need here
htmlarr.push($(this).clone().wrap('<div>').parent().html());
})
Demo - http://jsfiddle.net/tJ2Zc/
The code uses this method $(this).clone().wrap('<div>').parent().html() to get the outer HTML of a DOM element. More info can be found in the question - Get selected element's outer HTML
The code above writes all the radio button html into an array but you could change it to do what you wished within the loop.