Removing all dynamic 'data attributes' of an Element [duplicate] - javascript

This question already has answers here:
Remove multiple html5 data-attributes with jquery
(7 answers)
Closed 8 years ago.
I have a div where dynamic data- attributes get added on some tags.
(name of data- attributes to be generated dynamically by script, so there is no way my script will know the NAME of data-attribute)
<div data-1223="some data" data-209329="some data" data-dog="some value"> </div>
Now, I want to write a code in which it resets the div by removing all the data attributes and their values.
I can use
$('div').attr('data-209329',"")
but the problem is I don't know the name of data-attribute that will be added.
the data-attribute that will be added is dynamic and I don't have control of it.
removing div and reinserting div is not an option.
Pls help.
thanks in advance

YOu can use like this
var data = $("div").data();
var keys = $.map(data, function (value, key) {
return key;
});
for (i = 0; i < keys.length; i++) {
$("div").removeAttr("data-" + keys[i]);
}
Fiddle
Edit
Suggested by #Mottie
$.each($('div').data(), function (i) {
$("div").removeAttr("data-" + i);
});
Demo

You can use this code :
var data = $('div').data();
for(var i in data){
//for change
$('div').attr("data-"+i,"something");
//for remove
$("div").removeAttr("data-" + i);
}
The $('div').data(); prepare a list of all data attributes in var data variable.
Then you can work with it.
This is fiddle of this solution.
UPDATE
Suggested by #Mottie
$.each($('div').data(), function (i) {
//for change
$('div').attr("data-"+i,"something");
//for remove
$("div").removeAttr("data-" + i);
});

I think that the removeData() function is what you are looking for here. This will remove all data information stored on the element.
The .removeData() method allows us to remove values that were previously set using .data(). When called with the name of a key, .removeData() deletes that particular value; when called with no arguments, all values are removed. Removing data from jQuery's internal .data() cache does not affect any HTML5 data- attributes in a document; use .removeAttr() to remove those.
It will not however remove the actual attributes from the elements. In order to remove the actual attributes, you'll need to extract a list of the existing attributes. You could do this by inspecting the data() function of an element (before running removeData).
The data() function will return an object of key => value pairs that you can then use to remove the actual attributes from the element using removeAttr().

Related

Remove option from selected list based of index?

I have two select lists and based off the selected index of either one I need to remove the option at that index from both lists.
I have seen example of doing this for the currently selected option using the remove() function but that would only work for one list as the other list might have a different option selected or none at all.
Knowing just the index value is it possible to do this with JavaScript / jQuery? I already have the code that figures out which list to pull the index from and get that index value. I just have not found a way to specify an index value for the removal.
Code developed based off comment:
function RemoveCode(codeType)
{
var selectedProjectsField = $("#SelectedProjects");
var selectedProjectCodesField = $("#SelectedProjectCodes");
var selectedTasksField = $("#SelectedTasks");
var selectedTaskCodesField = $("#SelectedTaskCodes");
var selectedOptionIndex;
if (codeType == "Project")
{
selectedOptionIndex = $("#SelectedProjects :selected").index();
}
else
{
selectedOptionIndex = $("#SelectedTasks :selected").index();
}
alert(selectedOptionIndex);
selectedProjectsField.eq(selectedOptionIndex).remove();
selectedTasksField.eq(selectedOptionIndex).remove();
}
Using The :eq() Selector
You could use the :eq() selector to target a specific element by it's index and then call remove() to remove it from the DOM :
// Syntax Example: This will remove then (index)th option element
$('select option:eq(index)').remove();
So in your case, you would simply want to concatenate your selectedOptionIndex into the selector to target selector using one of the following :
// Remove a specific option of your SelectedProjects element
$('#SelectedProjects option:eq(' + selectedOptionIndex + ')').remove();
Example
You can see an interactive example here and demonstrated below :
This code should work:
$('#SelectedProjects option')[index].remove();
$('#SelectedTasks option')[index].remove();
or
selectedProjectsField.find('option')[selectedOptionIndex].remove();
selectedTasksField.find('option')[selectedOptionIndex].remove();

Deleting an element from JSON in javascript/jquery

I have a problem in deleting data from a JSON object in javascript. I'm creating this JSON dynamically and the removal shall also take place dynamically. Below is my JSON and the situation I'm in to.
{brands:[51,2046,53,67,64]}
Now, I have to remove 53 from this which I am calculating using some elements property, but I'm not able to remove the data and unable to find the solution for this situation. Please help me folks, thank you.
Try to use Array.prototyp.splice,
var data = { brands:[51,2046,53,67,64] };
data.brands.splice(2,1);
Since you want to remove an element from an array inside of a simple object. And splice will return an array of removed elements.
If you do not know the position of the element going to be removed, then use .indexOf() to find the index of the dynamic element,
var elementTobeRemoved = 53;
var data = { brands:[51,2046,53,67,64] };
var target = data.brands;
target.splice(target.indexOf(elementTobeRemoved),1);
You could write the same thing as a function like below,
function removeItem(arr,element){
return arr.splice(arr.indexOf(element),1);
}
var data = { brands:[51,2046,53,67,64] };
var removed = removeItem(data.brands,53);

remove everything that is inside the actual tag [duplicate]

Is it possible to remove all attributes at once using jQuery?
<img src="example.jpg" width="100" height="100">
to
<img>
I tried $('img').removeAttr('*'); with no luck. Anyone?
A simple method that doesn't require JQuery:
while(elem.attributes.length > 0)
elem.removeAttribute(elem.attributes[0].name);
Update: the previous method works in IE8 but not in IE8 compatibility mode and previous versions of IE. So here is a version that does and uses jQuery to remove the attributes as it does a better job of it:
$("img").each(function() {
// first copy the attributes to remove
// if we don't do this it causes problems
// iterating over the array we're removing
// elements from
var attributes = $.map(this.attributes, function(item) {
return item.name;
});
// now use jQuery to remove the attributes
var img = $(this);
$.each(attributes, function(i, item) {
img.removeAttr(item);
});
});
Of course you could make a plug-in out of it:
jQuery.fn.removeAttributes = function() {
return this.each(function() {
var attributes = $.map(this.attributes, function(item) {
return item.name;
});
var img = $(this);
$.each(attributes, function(i, item) {
img.removeAttr(item);
});
});
}
and then do:
$("img").removeAttributes();
One-liner, no jQuery needed:
[...elem.attributes].forEach(attr => elem.removeAttribute(attr.name));
Instead of creating a new jQuery.fn.removeAttributes (demonstrated in the accepted answer) you can extend jQuery's existing .removeAttr() method making it accept zero parameters to remove all attributes from each element in a set:
var removeAttr = jQuery.fn.removeAttr;
jQuery.fn.removeAttr = function() {
if (!arguments.length) {
this.each(function() {
// Looping attributes array in reverse direction
// to avoid skipping items due to the changing length
// when removing them on every iteration.
for (var i = this.attributes.length -1; i >= 0 ; i--) {
jQuery(this).removeAttr(this.attributes[i].name);
}
});
return this;
}
return removeAttr.apply(this, arguments);
};
Now you can call .removeAttr() without parameters to remove all attributes from the element:
$('img').removeAttr();
One very good reason to do this for specific tags is to clean up legacy content and also enforce standards.
Let's say, for example, you wanted to remove legacy attributes, or limit damage caused by FONT tag attributes by stripping them.
I've tried several methods to achieve this and none, including the example above, work as desired.
Example 1: Replace all FONT tags with the contained textual content.
This would be the perfect solution but as of v1.6.2 has ceased to function. :(
$('#content font').each(function(i) {
$(this).replaceWith($(this).text());
});
Example 2: Strip all attributes from a named tag - e.g. FONT.
Again, this fails to function but am sure it used to work once upon a previous jQuery version.
$("font").each(function() {
// First copy the attributes to remove.
var attributes = $.map(this.attributes, function(item) {
return item.name;
});
// Now remove the attributes
var font = $(this);
$.each(attributes, function(i, item) {
$("font").removeAttr(item);
});
});
Looking forward to 1.7 which promises to include a method to remove multiple attributes by name.
One-liner.
For jQuery users
$('img').removeAttr(Object.values($('img').get(0).attributes).map(attr => attr.name).join(' '));
One don't need to refer to the name of attribute to to id nowadays, since we have
removeAttributeNode method.
while(elem.attributes.length > 0) {
elem.removeAttributeNode(elem.attributes[0]);
}
I don't know exactly what you're using it for, but have you considered using css classes instead and toggling those ? It'll be less coding on your side and less work for the browser to do. This will probably not work [easily] if you're generating some of the attributes on the fly like with and height.
This will remove all attributes and it will work for every type of element.
var x = document.createElement($("#some_id").prop("tagName"));
$(x).insertAfter($("#some_id"));
$("#some_id").remove();
Today I have same issue. I think that it will be useful for you
var clone = $(node).html();
clone = $('<tr>'+ clone +'</tr>');
clone.addClass('tmcRow');

Is there a way to remove a specific value from an attribute using jquery?

I have a page that displays products. In the encompassing <ul> I have some jQuery that adds values to attributes (such as <ul id="products" subcategorynavids="someValue">).
When a user clicks a filtering link, the jQuery checks the contents of subcategorynavids and then only displays products below that have a navid that is listed.
What I'm having an issue with is when the attribute has more than one value listed, and the user clicks the filter link a second time (to disable it), I need to remove ONLY the value that is being disabled...
For example, if the page is set to <ul id="products" subcategorynavids="9007 8019 7365"> and the user clicks the filter that enables/disables navid="8019", how do I remove the '8019' and leave the '9007' and '7365'?
I know there is .removeAttr(), .removeProp(), but those only remove the attribute ENTIRELY (right?).
I tried the following (which, as expected, didn't work)...
$("#products").attr('subcategorynavids').remove('8019');
There's no built-in jQuery way to do this, you'll have to do it manually.
$('#products').attr('subcategorynavids', function (_, val) {
return jQuery.grep(val.split(' '), function (val) {
return val !== '8019';
}).join(' ');
});
Here we use the callback way of using attr() to update an attribute. Inside the function, we split the current value val by ' ', and then filter the resulting array for those that aren't 8019 using jQuery'sgrep() function*, and the join the array back together and return it to be the new value of subcategorynavids.
* I'd want to use Array's filter() method, but it's not supported in all modern browsers, so you might as well use grep().
In this case, you could just use .replace()
var $attrs = $("#products").attr('subcategorynavids');
$("#products").attr( 'subcategorynavids', $attrs.replace( '8019', '' ));
use .replace()
$("#products").attr('subcategorynavids',$("#products").attr('subcategorynavids').replace('8019 ',''));
http://jsfiddle.net/laupkram/fg3dn/
Try this
var attr = $("#products").attr('subcategorynavids');
$("#products").attr('subcategorynavids', attr.replace('8019',''));
First get the values in that attribute and filter out the key word and again set the new attribute.. simple as that

Why do you have to re-select a JQuery element from a collection?

I have a number of check-boxes on my page, each has a name attribute for its useful value.
I want to get a list of values for the checked items only. I can get a collection of elements like so...
var checkedItems = $(".checkbox:checked");
Now I want to create the list (string) so I create a loop...
var list = "";
for (var i = 0; i < checkedItems.length; i++) {
list += $(checkedItems[i]).attr("name") + "\n";
}
This works and gives me my list. But the question is, why do I have to apply the JQuery object thingy i.e. $(...) to use the attr property?
if I had the following instead it would not work...
list += checkedItems[i].attr("name") + "\n";
But surely the array should be a collection of JQuery elements already? Why re-cast?
Here is a JSFiddle of the working example if anybody wants to try it
EDIT: Why does this work...
var item = $("#item");
var name = item.attr("name");
checkedItems[i] is a raw DOM element, not a jQuery object.
To get a jQuery object for a given element in the set, call checkedItems.eq(i).
You can do this more nicely by writing
var list = $(".checkbox:checked")
.map(function() { return this.name; })
.get()
.join('\n');
The code in your question is wrong, because
$(checkedItems[i].attr("name"))
should really be
$(checkedItems[i]).attr("name")
Besides that, you should really do it like this
var list = "";
checkedItems.each(function(){ list += this.name + '\n'; });
Demo at http://jsfiddle.net/dGeNR/2/
The reason it would not work, is that when you access the elements in the jQuery object with [] you get back a direct reference to the DOM element, and not another jQuery object.
I presume that what you actually do is this:
list += $(checkedItems[i]).attr("name") + "\n";
checkedItems is a jQuery selection. It contains references to the elements that it contains. These elements can be manipulated by jQuery methods, or accessed directly with checkedItems[n], where n is a 0-based index.
Those properties are not jQuery selections: they are the native DOM elements. If you want to use a jQuery method like attr, you need to create a new jQuery object, wrapping that native object.
In this case, you can avoid that by using the eq method, which gets a jQuery selection from an original selection by using a numeric key:
list += checkedItems.eq(i).attr('name') + "\n";
Even better in your case would be to use a combination of map and get and Array.prototype.join:
var list = checkedItems.map(function() {
return this.name;
}).get().join('\n');
Well the list-building code in your question doesn't work; it should be:
for (var i = 0; i < checkedItems.length; i++)
list += $(checkedItems[i]).attr("name") + "\n"; // or just checkedItems[i].name
The ".attr()" function is just defined to return the attribute value for the first element in the list of matched elements. It could have been designed to return an array (like the ".pluck()" function in the Prototype library), but it just doesn't work that way.
The ".css()" jQuery method is similar in that regard, as is ".val()".
Another way to do what you want is:
var list = checkedItems.map(function() {
return this.name;
}).get().join('\n'); // thanks SLaks :-)
To be able to call jQuery functions, you need to wrap the content in $() or jQuery().
I have fixed the example at http://jsfiddle.net/dGeNR/1/
You need to use list += $(checkedItems[i]).attr("name") + "\n";

Categories