How can I find an element by onclick attribute value? - javascript

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

Related

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

Get the tagName element inside class

I want to get the element of a inside class and change it.
My HTML is:
<div class="alignleft">
« Older Entries
</div>
I want to change Older Entries to Previous.
My JavaScript code is:
var oldentries = document.querySelector('.alignleft');
var ainside = document.getElementsByTagName('a');
oldentries.ainside.innerHTML = "Previous";
but that gives me undefined.
Once you use Document.querySelector() to get the elements with class '.alignleft' you can also do oldentries.querySelector('a'); to get the 'a' element within oldentries and then change the element.innerHTML:
var oldentries = document.querySelector('.alignleft'),
ainside = oldentries.querySelector('a');
ainside.innerHTML = 'Previous';
<div class="alignleft">
« Older Entries
</div>
You need to update the textContent property of the <a> element.
Working Example:
var linkElement = document.querySelector('.alignleft a');
linkElement.textContent = 'Previous';
<div class="alignleft">
<a>Older Entries</a>
</div>
You can look for your element using a signle call to querySelector by using a more precise selector : Directly use .alignLeft a instead of doing it twice.
This code works :
var entries = document.querySelector('.alignLeft a');
entries.innerHTML = "Previous"
Your code would render out to something like
document.querySelector('.alignleft').document.getElementsByTagName('a').innerHTML = "Previous";
Also, getElementsByTagName('a') would render an Array not an object which you can apply .innerHTML to.
var ainside = document.querySelector('.alignlef a'); // Select first occurance of a inside the first occurance of .alignleft in the document
ainside.innerHTML = "Previous";
document.getElementsByTagName returns a HTML Collection. So you need to iterate over it (in your case it would be the first entry).
var oldentries = document.querySelector('.alignleft');
var ainside = document.getElementsByTagName('a');
for(i=0;i<ainside.length;i++) {
ainside[i].innerHTML = "Previous";
}

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.

Remove character from div id

I need to remove the tag within this div id. What am I doing wrong here?
function thanksForHelping(div){
var siblingOne = $(div).next();
var siblingTwo = $(div).next().next();
var NIDsiblingOne = siblingOne.substring(1);
var NIDsiblingTwo = siblingTwo.substring(1);
}
I want to see:
siblingOne == #yo
siblingTwo == #hi
NIDsiblingOne == yo
NIDsiblingTwo == hi
However I am receiving this error in my console:
TypeError: siblingOne.substring is not a function
.next() returns a jQuery object (docs), which is why you cannot call substring() on it. If you want the id, you need to use attr() or prop():
$(div).next().attr('id'); // or prop()
although it's a little unclear exactly what you're going for, but hopefully this should point you in the right direction.
It looks like you're saying you have some div like <div id="#myid"> This is incorrect. You shouldn't have the # in the id; that's just how it's referenced in CSS queries.
But, you could be using links to link to that div like this: <a href="#myid"> in which case you would want to strip the # to get the proper value if you were going to target with something like getElementById()
Even so, you're calling substring on a jQuery object, not on the id itself. Try something like:
function thanksForHelping(div){
var siblingOne = $(div).next(), siblingTwo = siblingOne.next();
var existingIdOne = siblingOne.attr("id");
var existingIdTwo = siblingTwo.attr("id");
var noHashIdOne = existingIdOne.replace(/^#/, ''); //Using regex here in case it doesn't actually have a leading #
var noHashIdTwo = existingIdOne.replace(/^#/, '');
}
If you were doing the link thing that I mentioned before, you'd have two ways to approach it: 1) Fetch the actual id like I show above, or use jQuery and just use the version with the hash. So, something like this:
function elementsForIntraPageLinks(){
var links = $("a.internal");
links.each(function(i, link) {
var href = link.href;
var targetElement = $(href);
console.log("targetElement:", targetElement);
});
}
or without jQuery but in a modern browser:
function elementsForIntraPageLinks(){
var links = document.querySelectorAll('a[href^="#"]');
links.forEach(function(link, i, links) {
console.log("targetElement:", document.querySelector(link.href));
});
}
or in a slightly older browser
function elementsForIntraPageLinks(){
var links = document.getElementsByTagName('a'), i, ii, link;
for(i = 0, ii = links.length; i < ii; i++){
link = links[i];
if (/^#/.test(link.href)) {
console.log("targetedElement", document.getElementById(link.href.replace(/^#/, ""));
}
});
}

Javascript innerHTML updating issue

I have the following JavaScript line:
<div id="box" name="1" margin="4px" padding="4px" onclick="memory(1)"></div>
With the associated memory() function being:
function memory(a) {
var tmpDar = a-1;
var m = document.getElementsByName(tmpDar);
m.innerHTML = arrA[tmpDar];
}
However, when I try executing the code, the HTML doesn't alter... Can somebody please help me?
document.getElementsByName() returns a NodeList and not a single element!
So in order to set the innerHTML of your div, you have to reference an entry inside that array, e.g., like this:
function memory(a) {
var tmpDar = a-1;
var m = document.getElementsByName(tmpDar);
m[0].innerHTML = arrA[tmpDar];
}
In your code you set the innerHTML property for the NodeList object, which has no (visual) effect in the document.
In general it would be better to use id instead of name. Then you could use document.getElementById() in a way like this:
function memory(a) {
var tmpDar = a-1;
var m = document.getElementById(tmpDar);
m.innerHTML = arrA[tmpDar];
}
document.getElementsByName returns an array. So if the element that you want is unique with this name, you should replace your code by :
function memory(a) {
var tmpDar = a-1;
var m = document.getElementsByName(tmpDar);
m[0].innerHTML = arrA[tmpDar]; // Here I have added index 0
}
your trying to find all elements with a name of 0 as far as I can tell. And there is no 0 name.
Also what the other two said, it returns an array you need to call an index on that array.

Categories

Resources