Get element attribute from array - javascript

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")

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(/^.*[\\\/]/, '');
});

Using JQuery's .attr() When Selector Returns Multiple elements

I am trying to pull 2 pieces of data from each of several fields. All the fields have been given the same "name" so as to allow them to be referenced easily.
<input type="text" name="common_name" data-X='ABC'>
The first piece of data I am pulling is their values, which does seem to be working. My issue is when I try to use attr(). It just stops dead in the water at that point.
var length = $('[name=common_name]').size();
for(var i=0; i < length; i++){
var value = parseInt($('[name=common_name]').get(i).value); //doesn't kill the script
var dataX = $('[name=common_name]').get(i).attr('data-X'); //Script is killed here
}
Since I'm not having issues with using attr() in general when the selector is selecting the element based on an id, I would think the issue has to do with the fact that in this case multiple elements are being returned by jQuery. What I am confused by is that I thought that get(#) is supposed to grab a specific one…in which case I don't see what the problem would be. (After all, using get(#) DOES work when I use val()).
So…why doesn't attr() work here?
.get() returns a dom element reference which does not have the .attr() method, so you can use the .eq() method which will return a jQuery object
var length = $('[name=common_name]').size();
for (var i = 0; i < length; i++) {
var value = parseInt($('[name=common_name]').eq(i).val()); //doesn't kill the script
var dataX = $('[name=common_name]').eq(i).attr('data-X'); //Script is killed here
}
The correct way to iterate over an jQuery object collection is to use the .each() method where the callback will be invoked for each element in the jQuery collection
$('[name=common_name]').each(function () {
var $this = $(this);
var value = parseInt($this.val()); //or this.value
var dataX = $this.attr('data-X'); //or $this.data('X')
})
Suppose the html is like this
<input type="text" name="common_name" data-X='ABC'>
<input type="text" name="common_name" data-X='DEF'>
<input type="text" name="common_name" data-X='GHI'>
Now the script part
$('input[name="common_name"]').each(function() {
var el = $(this);
text_val = el.val();
data = el.attr('data-X');
console.log(text_val);
console.log(data);
});
attr is a jquery fn, should call by jquery object
use like this
$('[name=common_name]').attr('data-X')
so try
dataX = $($('[name=common_name]').get(i)).attr('data-X');

Selecting inside a DOM element

This is the html code
<div class="extra-sub-block sub-block-experience">
<h6 style="display:inline;" id="exp-pos-0" class="extra-sub-block-head sub-block-head-experience">CEO</h6>
</div>
<div class="extra-sub-block sub-block-experience">
<h6 style="display:inline;" id="exp-pos-1" class="extra-sub-block-head sub-block-head-experience">COO</h6>
</div>
There are several such similar structures. Now I try to extract the values from each block.
var temp=document.getElementsByClassName('sub-block-experience');
var result=$(temp[0]+"#exp-pos-0");
This throws an error. I followed selecting element inside another DOM
I also tried
var temp=document.getElementsByClassName('sub-block-experience');
var result=temp[0].find('h6');
This doesn't work as well. What am I doing wrong here. Help?
For extracting the values from all blocks, you can use .map() function as follows:
var results = $('.extra-sub-block-head').map(function(){
return $(this).text();
})
Demo
side note: Since id is unique in a document, you can directly access the element using id selector like var result= $("#exp-pos-0");instead of var result=$(temp[0]+"#exp-pos-0");
Try, var result=$(temp[0]).find('h6');
Even, in the documentation link that you gave in question, it shows that you should wrap your result from document.getElementById in $() to be applied with jQuery. What it does is, that it converts the native javascript object into a jquery object.
Demo
function testIt(){
var tags, index;
tags = document.getElementsByTagName('h6');
for (index = 0; index < inputs.length; ++index) {
//do something ...
}
}
If I am correct you are trying to get ceo and coo?.If that's the case then with jquery:
var x= $('.extra-sub-block h6');
//values are
$(x[O]).html();
$(x[1]).html();
You could also use plain javascript:
var result = document.querySelectorAll('.sub-block-experience h6');
Or if you like it separate:
var temp = document.querySelectorAll('.sub-block-experience');
var result = [];
for(var i = 0, elem; elem = temp[i]; i++) {
result = result.concat(elem.querySelectorAll('h6'));
}
But be aware of the browser compatability of querySelectorAll and querySelector.

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

How to remove data- attribute from the div element?

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);

Categories

Resources