Put all element values in an array - javascript

I have the following markup:
<div class="class1"><p>line1</p><p>line 2</p></div>
With jQuery, how can I take the values of all the p tags within the div and place them in an array?

Use .map():
var arr = $('.class1 p').map(function () {
return $(this).text();
}).get();

I will assume you mean the contents of the <p> elements, not their value (which is nothing).
var text = [];
$('.class1 > p').each(function() {
text[text.length] = $(this).text();
});

Related

How can I get an element by it's closest matching text?

I have multiple h3 which as various text in it. i would like to select an element by it's text content. but i don't receive the exact text matching from back-end.
but i have partly machable text with me. using this how can i select the respected element.
example html :
<h3>civil</h3>
<h3>mechanical</h3>
<h3>electrical</h3>
js :
var text = "civil engineering";
var element = $('h3').closest(":contains('"+text+"')");
console.log(element);
here i have var text = civil engineering using this i would like to select the h3 element.
Not only matching this, there is much. i would like to match the text the closest.
Live Demo
In I understood correctly
You need to use .filter() in combination with indexOf()
var text = "civil engineering";
var element = $('h3').filter(function(){
return text.indexOf($(this).text()) != -1;
});
$(document).ready(function() {
var text = "civil engineering";
var element = $('h3').filter(function() {
return text.indexOf($(this).text()) != -1;
});
console.log(element.text());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h3>civil</h3>
<h3>mechanical</h3>
<h3>electrical</h3>
You can use indexOf() function:
var h3 = $('h3');
var str = 'civil engineering';
h3.each(function() {
if (str.toLowerCase().indexOf($(this).text()) >= 0) {
$(this).addClass('found');
}
});
Every h3 that contains the string you set, gets class .found

jQuery hide inner html, except for a tags

I have the following HTML:
<div class="content-body attribute-pdf">
<a href="/_fragment/content/download/296/1935/file/blabla.pdf">
blabla.pdf</a> 1.2 Mb
</div>
This is coming out of a CMS, and I would like to hide this "1.2 MB",but still keep the A href part
is this possible to do in jQuery ?
I tried this:
$(".attribute-pdf").children().hide();
which hides the A href, but still shows the text. I want it vice-versa - hide the text, but still show the A href.
A quick way, in jQuery - empty the div, replace its contents with just the <a> tag:
$('.attribute-pdf').each(
function() {
var container = $(this);
var a = container.find('a').detach();
container.empty().append(a);
}
);
Example: http://codepen.io/paulroub/pen/iaFnK
You could set the contents of the parent to be the contents of the childeren ...
$(".attribute-pdf").each(function(){
var $this = $(this); // cache for performance
$this.html($this.children());
});
grab the content ( a link ) , empty the div ( removes 1.2 mb ) and again append a link.
http://jsfiddle.net/vpVMK/
var content = $(".attribute-pdf a");
$(".attribute-pdf").html('');
$(".attribute-pdf").append(content);
you could do:
// contents() gives children, all including non-element nodes.
// Then, we can filter those down to the final text one.
var textNodes = $( ".attribute-pdf" ).contents().filter(function() {
return this.nodeType === 3;
});
var lastTextNode = textNodes.last();
//and replace
lastTextNode.replaceWith('');
You could do this:
var children = $(".attribute-pdf").children();
$(".attribute-pdf").html(children);
http://jsfiddle.net/H2WVt/
Here is another method that hasn't been posted yet:
$(".attribute-pdf").html(function(){
var $this = $(this),
$tmp = $('<div>');
return $.makeArray( $this.children('a').map(function() {
$tmp.html(this)
return $tmp[0].innerHTML
}) ).join('')
})
The fiddle

How can I get td first child value?

I have a table where I want, for each row, get the first td and for this td I want the first input child value.
I'm able to get the markup for the input, but I can't extract the value.
Here is my code:
$('#table-unidades tr:not(:last-child)').each(function () {
$('td:first-child', this).each(function () {
var firstCell = $(this).children().eq(0);
var text = firstCell.html();
alert(text);
})
});
my alert outputs this:
<input type="text" name="unidades-first-td" value="UN - Unidade" disabled />
But all I want is the value.. I've tried with .text(), .val() , but it didn't work...
try this and get them all as an array once:
$("#table-unidades tr:not(:last-child)>td:first-child input:text:first-child")
.map(function () {return $(this).val(); }).get();
You need to use val() to get value of input, then use find() to find input field inside td
$('#table-unidades tr:not(:last-child)').each(function() {
$('td:first-child', this).each(function() {
var firstCell = $(this).children().eq(0);
var text = firstCell.find('input').val();
alert(text);
})
});
You don't need to use two each loops to find first child, also you must use .val() to get the value of an input, try this
$('#table-unidades tr:not(:last-child)').each(function () {
var text = $(this).find('td:first input:first').val();
});
Try
var val = firstCell.find('input').val();
alert(val);
Use .val() to get the value of the input element
$('#table-unidades tr:not(:last-child) td:first-child').each(function () {
var firstCell = $(this).children('input');
var text = firstCell.val();
alert(text);
});
var trs = $("tr", ".my-table");
for(var i=0; i<trs.length; i++){
var nval = $("td:first-child > input", trs[i]).val();
console.log(nval);
}
1 don't care about the reputation.
2 if it doesn't work, make it work.

Find and list every element's id value

I'm trying to get all the found elements within a <div>, but by default it stops when it found the first occurrence, but I want it to list every found element's id value.
So this doesn't work:
listy = $("DIV").find("SPAN").attr("id");
I've been experimenting with .get and .map, but I think they're not what I want..
listy = $("div").find("span").map(function(){
return this.id;
}).get();
Without find is even better:
listy = $("div span").map(function(){
return this.id;
}).get();
Live DEMO
If you want only <span> with id attribute defined, change the selector to:
$(div span[id]).map(...)
If you want all the ids as a string:
listy = $("div span").map(function(){
return this.id;
}).get().join('');
The parameter of join is the delimiter, e.g. .join('-') or .join(',') or without: .join('')
Maybe this way?
var ids = [];
$("div span").each(function() {
if (this.id) {
ids.push(this.id);
}
});
attr() method will always return first elements attribute only.
var listy = '';
$("div span").each(function(){
listy += this.id ;
});
jsBin demo
Or like:
var listy = []; // create array
$("div span[id]").each(function(){ // span with ID data
listy.push( this.id ); // push ID names into array
});
// Now use listy.join(); to see the list
// you can also do: listy+'' to transform it into string.
jsBIn demo 2

How to get div text also with it's input's values

I was wondering how to obtain the text inside a given div, with also the input's values as text.
<div id="example">This is a <input type="text" value="right"/> test.</div>
If I just try to get text like this with jQuery :
$("#example").text();
The result would be This is a test. and I'd want : This is a right test.
The number of input would be unknow. As well as the order of the elements...
EDIT :
I finally resolved my own problem :
var finalText="";
$("#example").contents().filter(function() {
if(this.nodeType==3){ finalText =finalText+ this.nodeValue;}
else if(this.nodeName=="INPUT"){ finalText=finalText+this.value;}
return finalText
})
The living example
But #Jonathan Lonowski answer is more clear and simpler than mine !
Here is a quick plugin that will do this for you:
$(document).ready(function() {
$.fn.extend({
getContentText: function() {
var t = '';
this.contents().each(function(i,c) {
var method = $(c).is("input") ? "val" : "text";
t += $(c)[method]();
});
return t;
}
});
alert($("#example").getContentText());
});
Try it out here:
http://jsfiddle.net/wQpHM/
You might try cloning so you can replaceWith the inputs with their values. Then grab the text as you were:
var clone = $('#example').clone();
clone.find(':input').replaceWith(function () {
return $(this).val();
});
alert(clone.text());
You can loop though all children of the <div> and replace then with their values. Something like this:
$.fn.allText = function(){
var $this = this.clone();
$this.children().each(function(){
$(this, $this).replaceWith(this.value);
});
return $this.text();
};
alert($('#example').allText());
Demo: http://jsfiddle.net/4mGmH/
get html and strip html tags
$('#example')[0].innerHTML.replace(/(<([^>]+)>)/ig, '').replace(/(\s+)/g, ' ')
Using innerText
document.getElementbyId('example').innerText;
To get HTML tags:-
document.getElementbyId('example').innerHTML;
Refer this URL element.innerHTML

Categories