I have to find and display a selector from HTML presented in array, this works for me using Jquery:
var a = '';
var b = Array.prototype.map.call($('p', a),
function(e) { return e.outerHTML; });
console.log(b)
However I don't want to use Jquery, Id rather use plain Javascript so I tried:
a.querySelectorAll('p')
Not working. Why is that and what else can I try?
You're using querySelectorAll as if it is available in the String.prototype object because the variable a is an empty string.
Try document.querySelectorAll('p');
I think what you want is this:
var b = Array.prototype.map.call(document.querySelectorAll("p"),
function(e) { return e.outerHTML; });
console.log(b);
This way your calling the query selector on the document rater than on an empty string(where the function won't exist).
Try this:
document.getElementsByTagName("p")
Which will return an array of all <p> tags
Related
I have what I am sure is a very straightforward question! I have an xml document and, using AJAX, I am wanting to get the values from tags with the same name into an array. XML:
<data>
<instance>
<term>Dog</term>
<clicks>11235</clicks>
</instance>
<instance>
<term>Cat</term>
<clicks>6309</clicks>
</instance>
</data>
My Javascript:
console.log(xml.getElementsByTagName("clicks")[0].childNodes[0].nodeValue);
This only seems to return the first value. How do you return them all?
Try i wrote in java, I think you have to change the array part. hope this helps.
NodeList clicks = xml.getElementsByTagName("clicks")
int[] clickArray = new int[clicks.getLength()];
for(int i=0; i<clicks.getLength();i++){
clickArray[i] = clicks[i].childNodes[0].nodeValue;
}
function test(){
var clicks = xml.getElementsByTagName("clicks");
var result = new Array();
foreach(var c in clicks){
console.log(c);
result.push(c.childNodes[0].nodeValue);
}
return result;
}
this should print all "click" tags. In your result array now are all values, but note that this just works, if the tag "structure" is always the one you posted above
You can use jQuery to get all tags, and then use .each() to get all values:
$(xml).find('clicks').each(function(){
console.log($(this).html());
});
or if you want to get an array, you can use .map() function:
var list = $(xml).find('clicks').map(function(){
return $(this).html();
}).get();
Using d3.js you can do something like this:
Define a div in your DOM <div></div>
var list = d3.select('div')
.html(xml) // set the xml content
.selectAll('clicks')
.each(function(){
console.log(this.innerHTML);
});
console.log(list); //you can do what you want with all clicks elements
How do you convert a jQuery object into a string?
I assume you're asking for the full HTML string. If that's the case, something like this will do the trick:
$('<div>').append($('#item-of-interest').clone()).html();
This is explained in more depth here, but essentially you make a new node to wrap the item of interest, do the manipulations, remove it, and grab the HTML.
If you're just after a string representation, then go with new String(obj).
Update
I wrote the original answer in 2009. As of 2014, most major browsers now support outerHTML as a native property (see, for example, Firefox and Internet Explorer), so you can do:
$('#item-of-interest').prop('outerHTML');
With jQuery 1.6, this seems to be a more elegant solution:
$('#element-of-interest').prop('outerHTML');
Just use .get(0) to grab the native element, and get its outerHTML property:
var $elem = $('Some element');
console.log("HTML is: " + $elem.get(0).outerHTML);
Can you be a little more specific? If you're trying to get the HTML inside of a tag you can do something like this:
HTML snippet:
<p><b>This is some text</b></p>
jQuery:
var txt = $('p').html(); // Value of text is <b>This is some text</b>
The best way to find out what properties and methods are available to an HTML node (object) is to do something like:
console.log($("#my-node"));
From jQuery 1.6+ you can just use outerHTML to include the HTML tags in your string output:
var node = $("#my-node").outerHTML;
jQuery is up in here, so:
jQuery.fn.goodOLauterHTML= function() {
return $('<a></a>').append( this.clone() ).html();
}
Return all that HTML stuff:
$('div' /*elys with HTML text stuff that you want */ ).goodOLauterHTML(); // alerts tags and all
This seems to work fine for me:
$("#id")[0].outerHTML
The accepted answer doesn't cover text nodes (undefined is printed out).
This code snippet solves it:
var htmlElements = $('<p>google</p>↵↵<p>bing</p>'),
htmlString = '';
htmlElements.each(function () {
var element = $(this).get(0);
if (element.nodeType === Node.ELEMENT_NODE) {
htmlString += element.outerHTML;
}
else if (element.nodeType === Node.TEXT_NODE) {
htmlString += element.nodeValue;
}
});
alert('String html: ' + htmlString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
No need to clone and add to the DOM to use .html(), you can do:
$('#item-of-interest').wrap('<div></div>').html()
It may be possible to use the jQuery.makeArray(obj) utility function:
var obj = $('<p />',{'class':'className'}).html('peekaboo');
var objArr = $.makeArray(obj);
var plainText = objArr[0];
If you want to stringify an HTML element in order to pass it somewhere and parse it back to an element try by creating a unique query for the element:
// 'e' is a circular object that can't be stringify
var e = document.getElementById('MyElement')
// now 'e_str' is a unique query for this element that can be stringify
var e_str = e.tagName
+ ( e.id != "" ? "#" + e.id : "")
+ ( e.className != "" ? "." + e.className.replace(' ','.') : "");
//now you can stringify your element to JSON string
var e_json = JSON.stringify({
'element': e_str
})
than
//parse it back to an object
var obj = JSON.parse( e_json )
//finally connect the 'obj.element' varible to it's element
obj.element = document.querySelector( obj.element )
//now the 'obj.element' is the actual element and you can click it for example:
obj.element.click();
new String(myobj)
If you want to serialize the whole object to string, use JSON.
I have this array:
var array = [{"a":"1","b":"2"},{"a":"3","b":"1"},{"a":"5","b":"4"}]
now i want to remove the line, lets say, where a=5. So afterwards the array looks like this:
var array = [{"a":"1","b":"2"},{"a":"3","b":"1"}]
How do i do this the easiest and fastest way?
You can use jQuery.map which allows you to return null for an element to be deleted.
eg:
var array = [{"a":"1","b":"2"},{"a":"3","b":"1"},{"a":"5","b":"4"}]
var newArray = $.map(array, function(e){
return (e.a == "5") ? null : e;
});
// newArray contains [{"a":"1","b":"2"},{"a":"3","b":"1"}]
Live example (watch the console): http://jsfiddle.net/2Yz7f/
Javascript (non jQuery) approach: http://jsfiddle.net/VYKBc/
Maybe this is your answer
array.splice(2,1);
I have an array on javascript and i insert the elements on it like this:
var parentRow = $(button).parent().parent();
list.push({ parent: parentRow, detailRow: newRow });
On the click of another button i do the following:
var parentRow = $(button).parent().parent();
var detailRow = null;
for (var i in list) {
if ($(list[i].parent) == $(parentRow)) {
detailRow = list[i].detailRow;
}
}
The point is: The if comparing to two elements should return TRUE, because they are the same DOM element....the same i added before, but it return FALSE.
I would like to know how i compare this two elements to get TRUE there.
Try:
if (parentRow.has(list[i])) {
They are not the same objects, because they don't refer to the same jQuery instance.
Simple solution: Don't use jQuery and do it with normal DOM methods.
jQuery solution: Use .is()
You need to compare the native elements, not the jQuery-wrapped elements. jQuery's DOM methods returns not the elements themselves but a jQuery object.
if (list[i].parent[0] === parentRow[0]) {
I want to loop over the elements of an HTML form, and store the values of the <input> fields in an object. The following code doesn't work, though:
function config() {
$("#frmMain").children().map(function() {
var child = $("this");
if (child.is(":checkbox"))
this[child.attr("name")] = child.attr("checked");
if (child.is(":radio, checked"))
this[child.attr("name")] = child.val();
if (child.is(":text"))
this[child.attr("name")] = child.val();
return null;
});
Neither does the following (inspired by jobscry's answer):
function config() {
$("#frmMain").children().each(function() {
var child = $("this");
alert(child.length);
if (child.is(":checkbox")) {
this[child.attr("name")] = child.attr("checked");
}
if (child.is(":radio, checked"))
this[child.attr("name")] = child.val();
if (child.is(":text"))
this[child.attr("name")] = child.val();
});
}
The alert always shows that child.length == 0. Manually selecting the elements works:
>>> $("#frmMain").children()
Object length=42
>>> $("#frmMain").children().filter(":checkbox")
Object length=3
Any hints on how to do the loop correctly?
don't think you need quotations on this:
var child = $("this");
try:
var child = $(this);
jQuery has an excellent function for looping through a set of elements: .each()
$('#formId').children().each(
function(){
//access to form element via $(this)
}
);
Depending on what you need each child for (if you're looking to post it somewhere via AJAX) you can just do...
$("#formID").serialize()
It creates a string for you with all of the values automatically.
As for looping through objects, you can also do this.
$.each($("input, select, textarea"), function(i,v) {
var theTag = v.tagName;
var theElement = $(v);
var theValue = theElement.val();
});
I have used the following before:
var my_form = $('#form-id');
var data = {};
$('input:not([type=checkbox]), input[type=checkbox]:selected, select, textarea', my_form).each(
function() {
var name = $(this).attr('name');
var val = $(this).val();
if (!data.hasOwnProperty(name)) {
data[name] = new Array;
}
data[name].push(val);
}
);
This is just written from memory, so might contain mistakes, but this should make an object called data that contains the values for all your inputs.
Note that you have to deal with checkboxes in a special way, to avoid getting the values of unchecked checkboxes. The same is probably true of radio inputs.
Also note using arrays for storing the values, as for one input name, you might have values from several inputs (checkboxes in particular).
if you want to use the each function, it should look like this:
$('#formId').children().each(
function(){
//access to form element via $(this)
}
);
Just switch out the closing curly bracket for a close paren. Thanks for pointing it out, jobscry, you saved me some time.
for me all these didn't work. What worked for me was something really simple:
$("#formID input[type=text]").each(function() {
alert($(this).val());
});
This is the simplest way to loop through a form accessing only the form elements. Inside the each function you can check and build whatever you want. When building objects note that you will want to declare it outside of the each function.
EDIT
JSFIDDLE
The below will work
$('form[name=formName]').find('input, textarea, select').each(function() {
alert($(this).attr('name'));
});