I have code like this:
$('#mb-history').on('click', '#post-edit .buttons .delete', function() {
var files = $('.files input:checked').map(function() {
return $(this).closest('.file');
});
var ids = files.map(function() {
return $(this).data('id');
}).get();
console.log(ids);
files.remove(); // this don't work
return false;
});
and files.remove() don't work the element stay in the DOM. (console.log show array with element I've selected). My html look like this:
<div class="files ui-helper-clearfix" style="display: block;">
...
<div class="file" data-id="13835">
<img src="/thumb.php?src=moja-budowa%2F611%2FMB_Z3_611_13835.jpg&size=90&height=64&nologo" alt="">
<input type="checkbox">
</div>
...
</div>
What's wrong with my code? I'm using jquery-1.8.2.
JSFIDDLE
I found, instead of map I can just put closest after set:
var files = $('.files input:checked').closest('.file')
You must have files references for removing or any other action.. $.map() create a new array. Change:
var files = $('.files input:checked').map(function() {
return $(this).closest('.file');
});
to
var files = $('.files input:checked').parent();
files
[
e.fn.e.init[1]
0: div.file
context: input
length: 1
prevObject: e.fn.e.init[1]
selector: ".closest(.file)"
__proto__: Object[0]
]
files[0].remove()
Related
function setParagraph(paraList) {
$.each(paraList, function (i, field) {
var pElement = document.createElement('p');
$(pElement).text(field);
//a line that combines the p elements like so:
//<p>First para</p>
//<p>Second para</p>
});
return //all elements for append;
}
I am trying to write code with minimum number of lines to return a "collection" of p elements that needs to be appended to the following div:
$("#somediv").append(setParagraph(jsonValue));
To produce:
<div id="somediv">
<p>First para</p>
<p>Second para</p>
</div>
The method setParagraph is passed json string with collection of string items that are translated into p elements in the method.
I have tried pushing the elements into an array but I don't think that is the right way to go.
Also, I do not wish to use string concatenation in the loop to produce the desired results, unless of course that is the only best way to handle it.
EDIT:
The below works but as I said I am looking for some other solution besides array:
function setParagraph(paraList) {
var arrElements = [];
$.each(paraList, function (i, field) {
var $pElement = $("<p/>").text(field);
arrElements.push($pElement);
});
return arrElements;
}
var jsonValue = ["First para","Second para"];
$("#somediv").append(setParagraph(jsonValue));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="somediv">
</div>
Shorter
const par = ["one", "two", "three"]
$("#somediv").html(par.map(p => $("<p>", { text: p })))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="somediv"></div>
You can use $.map(..) for that, here is an example:
function setParagraph(paraList) {
return $.map(paraList, function(item) {
return $("<p>", {
text: item
});
});
}
$("#somediv").append(setParagraph(["one", "two", "three"]));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="somediv"></div>
I've created a simple fiddle example that I think would suit your needs. It works in a different way, a little bit at least, but with a bit of changing you'd get your desired result.
Here's the fiddle: https://jsfiddle.net/fkoLn4v9/
Here's the code:
// index.js
const paragraphsCollection = [
{
tag: 'p',
content: 'This is the first parargraph',
},
{
tag: 'p',
content: 'This is the second paragraph',
},
];
const setParagraph = (parentElem, contentData) => {
contentData.forEach(({ tag, content }) => {
const domElem = document.createElement(tag);
domElem.innerText = content;
parentElem.appendChild(domElem);
});
};
const divElem = document.querySelector('.parentDiv');
setParagraph(divElem, paragraphsCollection);
HTML:
<div class="parentDiv"></div>
I need to find all elements in a page by attribute value only (ignoring the key) using jquery.
Is there a way to do this easily?
Currently, I am just iterating on all elements in the page, on every property etc..
You can use $.expr, Element.attributes, Array.prototype.some()
$.expr[":"].attrValue = function(el, idx, selector) {
return [].some.call(el.attributes, function(attr) {
return attr.value === selector[selector.length - 1]
})
};
// filter element having attribute with `value` set to `"abc"`
$(":attrValue(abc)").css("color", "blue");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div title="abc">abc</div>
<div title="def">def</div>
<div title="ghi">ghi</div>
<div title="jkl">jkl</div>
Use brackets []
var ElementsWithAttributeKeyTest = $('[attributeKey="Test"]');
Or pass an object with the attribute name and value as parameter to this function:
var getElemsByAttribute = function(obj) {
if (obj) {
if (obj.attributeKey && obj.attributeValue) {
return $('[' + obj.attributeKey + '="' + obj.attributeValue + '"]');
}
}
}
var attrObj = {
attributeKey: 'data-color',
attributeValue: 'red'
}
getElemsByAttribute(attrObj).css('color', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<span data-color="red">Red</span>
<span data-color="red">Red</span>
<span data-color="green">Green</span>
<span data-color="blue">Blue</span>
<span data-color="red">Red</span>
<span data-color="green">Green</span>
If you want to search all attributes values you can use this small plugin:
$.fn.search_by_attr_value = function(regex) {
return this.filter(function() {
var found = false;
$.each(this.attributes, function() {
if (this.specified && this.value.match(regex)) {
found = true;
return false;
}
});
return found;
});
};
and you can use it like this:
$('*').search_by_attr_value(/^some value$/);
Based on this answer
You could define new function take as parameter the value you want to filter with (e.g get_elements_by_value(filter)), then inside this function parse all the elements of the page using $('*').each(), after that parse the attributes of every element el of those elements using attribute attributes like below :
$.each(el.attributes, function(){ })
Then inside the each loop you could make your condition and push the matched values with the passed filter inside matched[] that should be returned.
Check working example below, hope this helps.
function get_elements_by_value(filter){
var matched=[];
$('*').each(function(index,el) {
$.each(el.attributes, function() {
if( this.value===filter )
matched.push(el);
})
})
return $(matched);
}
get_elements_by_value('my_value').css('background-color','green');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div title="my_value">AA</div>
<div title="def">BB</div>
<input type='text' name='my_value' value='CC'/>
<p class='my_value'>DD</p>
<span title="test">EE</span>
what I'm trying to do is iterate over a collection of div, contained in a parent container. My structure is the following:
<div id='main'>
<div data-id='2'>
</div>
<div data-id='3'>
</div>
</div>
My goal is take the field data-id of each div and create an array collection. Previously I used the select where do I get each value of available option, like this:
var available_services = $('#selected-service').find('option', this).map(function ()
{
return this.value;
}).get();
But now I'm using a div collection instead of the select. How I can iterate through all available div?
This should return all data-id values in a list:
var available_services = $('#main').find('div').map(function (item)
{
return item.attr('data-id');
});
I didn't test this, but I think should do the job. (maybe you need to tweak a little bit)
I believe this will do it:
var available_services = [];
$('#main div').each(function(){
available_services.push($(this).data( "id" ));
})
This is the easy way to go:
$(document).ready(function() {
var myCollection = [];
$('#main div').each(function(){
var dataDiv = $(this).attr('data-id');
myCollection.push(dataDiv)
})
});
Try this:
(function(){
var main = $("#main");
var divs = $(main).find("div");
var arrId = divs.map(function(index, div){
return $(div).attr("data-id");
});
console.log(arrId);
})()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id='main'>
<div data-id='2'>
</div>
<div data-id='3'>
</div>
</div>
I need to append this json data to an html element.
[
{
"website":"google",
"link":"http://google.com"
},
{
"website":"facebook",
"link":"http://fb.com"
}
]
How to convert this easily using any plugin.Presently,I couldn't find any simple plugins in jquery,So please help me friends.
Thanks in advance..........
Hi you can use jPut jQuery Plugin (http://plugins.jquery.com/jput/)
Create a HTML jPut Template
<div jput="template">
{{website}}
</div>
<div id="main">
</div>
<script>
$(document).ready(function(){
var json=[{"website":"google","link":"http://google.com"},
{"website":"facebook","link":"http://fb.com"}];
$('#main').jPut({
jsonData:json, //your json data
name:'template' //jPut template name
});
});
</script>
jPut is easy to use comparing to normal parsing.
if there is lots of data to be appended it is very difficult to append using $.each loop.
in jPut just need to create template & to print the data just put the object name in {{}}.
With jQuery, you could do something like this:
data = $.parseJson(json);
$.each(data, function(key, obj) {
htmlElement = $(''+website+'');
$('body').append(htmlElement);
})
Why use a plugin for this? No need to write a plugin to go around this. Just simply loop it through & do what you wan't with the data. Here is an example:
var data = [
{
"website":"google",
"link":"http://google.com"
},
{
"website":"facebook",
"link":"http://fb.com"
}
];
var html = '';
$.each(data, function (index, item) {
html += '' + item.website + '';
});
$('body').append(html);
If you're expecting it to be an anchor tag then -
Html -
<div id="siteContainer"></div>
JS-
var sites = [
{
"website":"google",
"link":"http://google.com"
},
{
"website":"facebook",
"link":"http://fb.com"
}
]
var $container = $('siteContainer');
$(sites).each(function(item, index){
var name = item['website'];
var link = item['link'];
var anchorTag = '' + name + '');
$container.appendTo(anchorTag);
});
NO need plugin, simply iterate with each function and append anchor tag with any selector tag.
var links = [
{
"website":"google",
"link":"http://google.com"
},
{
"website":"facebook",
"link":"http://fb.com"
}
];
$.each(links, function(index, object){
$("<a></a>").attr("href", object.link).
text( object.website).css("margin", "5px").appendTo("body");
})
no plugin needed, can be done without jquery too
<div id="container">
</div>
<script>
var data = [
{
"website":"google",
"link":"http://google.com"
},
{
"website":"facebook",
"link":"http://fb.com"
}
]
document.getElementById('container').innerHTML = ''+data[0]['website']+' >> '+data[0]['link']+' <br> '+data[1]['website']+' >> '+data[1]['link']
</script>
I have some HTML:
<div id="bin">
<span class="item1 selectMe">1</span>
<span class="item2 selectMe">2</span>
<span class="item3 dontSelectMe">3</span>
</div>
I would like to return an array with the values in the span elements which contain the selectMe class. This is what I've written:
var values = [];
$('#bin span.selectMe').each(function() {
values.push($(this).text());
});
However, when I print values to the console, it is always empty. Any thoughts on why I am not iterating through the bin?
What you have should work, but here is a more elegant solution:
var values = $('#bin span.selectMe').map(function() {
return $(this).text();
}).get();
The following should work, however what you paste above should seem to also:
var values = $('#bin span.selectMe').map(function(){
return $(this).html();
});
var values = [];
$('#bin').find('span.selectMe').each(function() {
values.push($(this).text());
});