How to remove data- attribute from the div element? - javascript

I have an html div element, which contains lot of HTML-5 data- attributes to store extra
data with element. I know that we can use removeAttr of jquery to remove specific attribute,
but i want to know that is there any way to remove data- all atonce?

No, you have to loop through them and remove them individually. E.g.:
var $div = $("selector for the div"),
attrs = $div[0].attributes,
name,
index;
for (index = attrs.length - 1; index >= 0; --index) {
name = attrs[index].nodeName;
if (name.substring(0, 5) === "data-") {
$div.removeAttr(name);
}
}
Live copy | source
...or something along those lines.

Not aware of any wholesale way of doing this. You'd have to loop over the element's attributes with something like
var el = document.querySelector('p');
for (var i=0; i<el.attributes.length; i++)
if (/^data-/i.test(el.attributes[i].name))
el.removeAttribute(el.attributes[i].name);

Related

jQuery: Giving elements in selector individual attributes

I want to replace all svg images on my page with other svg images with the same name, but in a different directory.
Specifically, the current images are in the img directory, I want to replace the source of the images to img/icon-black.
I get all the svg elements with the following selector:
$.svgSelector = $(document).find('img[src$=".svg"]');
I calculate the new sources with the following:
var newSources = $.svgSelector.map(function(){return $(this).attr("src");}).get();
for(var i = 0; i < newSources.length; i++) {
newSources[i] = newSources[i].replace(/^.*[\\\/]/, '');
newSources[i] = "img/icon-black/" + newSources[i];
}
The problem arises when I want to assign the new sources to the individual elements in the selector.
I want to do something like this:
for(var j = 0; j < newSources.length; j++) {
$.svgSelector[i].attr("src", newSources[i]);
}
i.e. assign the source of each individual element's in the selector to its corresponding new source.
This way does not work, however. .attr() only returns the first src in the selector, and you cannot use it on individual elements of the selector like this either. I have also tried the .each() function but I cannot figure it out.
How do I solve this?
Instead of having to map all the src attributes to a new array, and then iterating through the array to replace the values, and then rewriting the sources in yet another loop, you can all do it in a single iterative block:
$.svgSelector = $(document).find('img[src$=".svg"]');
$.svgSelector.each(function() {
newImageSrc = "img/icon-black/" + $(this).attr('src').replace(/^.*[\\\/]/, '');
$(this).attr('src', newImageSrc);
});
Even better: the .attr() function actually takes a callback. In that sense, you can even condense it further:
$(document).find('img[src$=".svg"]').attr('src', function(i, src) {
return "img/icon-black/" + src.replace(/^.*[\\\/]/, '');
});

Get element attribute from array

The objective is to create multiple sliders on the page by linking the slider to something. The slider must be activated by clicking or hovering the slider anchor. sliderList would be a array for making this process easier so i wouldn't have to link each other manually on the configs js file.
I need to get the attribute value from a element that is inside an array. In this case, holder is the array from where I want to extract the attribute value from the current array element. I tried doing this:
var holder = $('[slider-select]');
for (var i = 0; i < holder.length; i++) {
var sliderList = $('[slider-target='
+holder[i].attr('slider-select')
+']');
}
It looks like +holder[i].attr('slider-select') isn't working. I'm learning JavaScript/Jquery and it's crazy how things goes wrong even when it makes all sense, lol. Let me know if I wasn't clear enough.
The function attr is a built-in function from jQuery, it's a shorthand of function getAttribute and setAttribute.
In your case you want to do this:
var holder = $('[slider-select]');
for (var i = 0; i < holder.length; i++) {
var test = holder[i];
var sliderList = $('[slider-target=' + holder[i].getAttribute('slider-select') + ']');
} ^
A good approach is to use the jQuery built-in functions, so you can use this:
$('[slider-select]').each(function() {
var sliderList = $('[slider-target=' + $(this).attr('slider-select') + ']');
}); ^
Resources
.attr()
getAttribute
setAttribute
.each()
holder[i] contains a plain DOM element, but you're trying to use the jQuery attr method on it. You need to convert it into a jQuery object $(holder[i]) (or else use the native getAttribute on the DOM element):
var holder = $('[slider-select]');
for (var i = 0; i < holder.length; i++) {
// Splitting this up a bit just to make it more readable:
var val = $(holder[i]).attr('slider-select'); // instead of holder[i].attr(...)
var sliderList = $('[slider-target="' + val + '"]');
// confirm we got the element:
console.log(sliderList.text());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div slider-select="A">A</div>
<div slider-select="B">B</div>
<div slider-select="C">C</div>
<div slider-target="A">a</div>
<div slider-target="B">b</div>
<div slider-target="C">c</div>
The attr method is not a function on the JS element object. You'll want to wrap it in jquery to retrieve attribute values instead. For instance
$(holder[i]).attr("slider-select")

How can I find an element by onclick attribute value?

I am wondering if it is possible to find an element by the onclick function?
For example:
<a class = "calculator" onclick = add(number1,number2);
<a class = "calculator" onclick = add(number2, number3);
And I want to get the first one and the only difference is the onclick function so I thought thats the way I could differ them. Looks so far like this:
var elements = document.getElementsByClassName("calculator");
console.log(elements);
for (var i = 0; i < elements .length; ++i) {
elementsSpecific = elements[i]. //The missing part
console.log(delementsSpecific);
}
You can, though I wouldn't recommend it. It's faster to use different ids. However, if you really want to do it this way...
var link = document.querySelector('a[onclick="add(number1,number2)"]');
If you don't understand it, read about querySelector
You can get the onclick function by using
elements[i].getAttribute('onclick');
This is a pretty poor way of targeting elements (what if the onclick value changes?) but if it's all you've got then you can use an attribute selector and querySelector:
var el = document.querySelector('a[onclick="add(number1,number2);"]');
I would definitely exhaust other avenues of selection before resorting to this, however.
Without using js frameworks and making it for crossbrowser you can do this.
var as = document.getElementsByClassName('calculator');
var element = null;
for (var x = 0; x < as.length; x++) {
if (as[x].getAttribute('onclick') == 'add(number2,number3)') {
element = as[x];
break;
}
}
http://jsbin.com/feyaheji/1/edit?html,console
document.querySelector is the holy grail of finding elements in the DOM:
HTML:
<a class = "calculator" onclick = "add(number1,number2);">First</>
<a class = "calculator" onclick = "add(number2, number3);">Second</>
JavaScript:
var d2 = document.querySelector('.calculator[onclick*=number2][onclick*=number3]');
var d1 = document.querySelector('.calculator[onclick*=number1][onclick*=number2]');
console.log('Second', d2);
console.log('First', d1);
Notice the [onclick*=number2] selector which matches elements with the attribute name onclick and the value containing number2

Want to set li innerHTML of ul

I'm writing a javascript function where I get a ul object from my HTML and want to set the text of one of the li elements in theul`. I'm doing:
list = document.getElementById('list_name');
Then I want to access the ith li element of list using a loop.
I have:
for (i = 0; i < 5; i++) {
list[i].innerHTML = "<a>text</a>";
}
but this is not working. What is the proper way to do it?
You need to access the child li elements of the ul. JavaScript and the DOM API can't automagically do that for you.
var list = document.getElementById('list_name'),
items = list.childNodes;
for (var i = 0, length = childNodes.length; i < length; i++)
{
if (items[i].nodeType != 1) {
continue;
}
items[i].innerHTML = "<a>text</a>";
}
You could also use getElementsByTagName('li') but it will get all descendent li elements, and it seems you want only the direct descendants.
You could also avoid innerHTML if you want.
var a = document.createElement('a'),
text = document.createTextNode('text');
a.appendChild(text);
items[i].appendChild(a);
innerHTML can cause issues, such as lost event handlers and the performance issue of serialising and re-parsing the HTML structure. This should be negligible in your example, however.
jQuery Sample code, although the others work:
$("#list_name li").text("<a href=''>text</a>");
Its much more succinct with jQuery
You can try the following
var el = document.createElement("li"),
content = document.createTextNode("My sample text"),
myUl = document.getElementById("ulOne");
el.appendChild(content);
el.id = "bar";
myUl.appendChild(el);
Here's the demo: http://jsfiddle.net/x32j00h5/
I prefer a aproach using getElemenetByTagName, if somehow you get a extra node like a script tag or a span you will have problems. A guess this code will help you:
var list = document.getElementById("mylist");
var items = list.getElementsByTagName("li");
for(var i = 0, size = items.length; i< size; i++){
items[i].innerHTML = "<a href='#'>LINK</a>";
}

How to get all element parents using jquery?

How to get all element parents using jquery? i want to save these parents in a variable so i can use later as a selector.
such as <div><a><img id="myImg"/></a></div>
GetParents('myImg'); will return "div a" something like that
/// Get an array of all the elements parents:
allParents = $("#myElement").parents("*")
/// Get the nested selector through an element's parents:
function GetParents(id) {
var parents = $("#" + id).parents("*");
var selector = "";
for (var i = parents.length-1; i >= 0; i--) {
selector += parents[i].tagName + " ";
}
selector += "#" + id;
return selector;
}
GetParents('myImage') will return your nested selector: HTML BODY DIV A #myImage
Note sure why you'd want this but its reuseable as a selector.
You don't need to grab their selectors, as you can use them directly with jQuery afterwards.
If you want to use all parents later, you can do something like:
var parents = $("#element").parents();
for(var i = 0; i < parents.length; i++){
$(parents[i]).dosomething();
}
Every element has only one real parent. To access and save it, write the following:
myParent = $("#myElement").parent();
If you need the parents parents too, use .parents()
See documentation for further information:
http://docs.jquery.com/Traversing/parent#expr
http://docs.jquery.com/Traversing/parents#expr
You can use parents() to get your immediate parent, and their parents on up the tree. you can also pass a selector as an arg to only get parents that match a certain criteria. For instance:
$('#myelement').parents('[id$=container]')
to get all parents who have an id attribute whose value ends with the text "container"
You can get all the tags of an element's parents like this:
var sParents = $('#myImg').parents('*').map(function() {
return this.tagName;
}).get().join(' ');
you can also replace this.tagName with this.id for example or other attributes

Categories

Resources