Jump to content

Search document.getElementsByClassNames(...) for href=..... (and not ID=....)


pstein

Recommended Posts

Assume I have an element defintion like:

 

<div class="aaa" href="#222" .....>.....</div>

 

Unfortunately there exist dozends of <div> element all with the same class.

The unique identifier for the target element is the attribute href=....

 

So in order to refer to the specifc element I have to use a command like

 

var div = document.getElementByHref("#222");

 

Unfortunately this command does not exist.

 

How else can I fetch excatly this element?

 

If necessary I can use jQuery, maybe with a statement similar to

 

var div = $(div.href="#222");

 

I don't know if this works

 

Peter

Link to comment
Share on other sites

The ways to do it with vanilla JS would be to get all elements with the class and just loop through them until you find the one you're looking for, or you can use document.querySelectorAll.

 

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

 

There are several different selectors you can use to check the value of an attribute:

 

http://www.w3schools.com/cssref/css_selectors.asp

Link to comment
Share on other sites

You should never have a div element with href attribute.

 

You can give a variable a ref to elements with class name

 

var elements_using_class = document.getElementsByClassName('aaa');

 

then loop through each looking at any other attribute value

elements_using_class = document.getElementsByClassName('aaa'); 
for(var=1;i<elements_using_class.length; i++)
{
if(elements_using_class[i].href==="#222")
{
alert("found "+elements_using_class[i].href)
}
}
With jQuery you can use attribute selector similar to css
$('a.aaa[href=#222]')
Edited by dsonesuk
  • Like 1
Link to comment
Share on other sites

The jQuery code from "dsonesuk" works but for possible future use I would like to investigate the "Data" solution from musicman as well.

 

However it seems to me that it is not correct.

 

Where does "#div1" come from?

 

Shouldn't it be:

 

$("div.aaa").data("href","#222");

 

?

 

Thank you

Peter

Edited by pstein
Link to comment
Share on other sites

The data() sets and retrieves data to specific element, but since the value you wish to retrieve already exists from an attribute, its a bit pointless as you are just duplicating this information.

 

The reason the id ref is used because its unique reference and can be used to target a specific element to retrieve specific data value, its difficult to retrieve specific value from multiple elements using same class references.

Link to comment
Share on other sites

Hi,

 

@dsonesuk said that the href value already defined with class attribute. But since we don't use href attribute in a div, and if the href value needed, I suggested to put the value in the element's data.

 

And you right, it supposed to be like $("div.aaa") :) my bad.

  • Like 1
Link to comment
Share on other sites

Because id ref is unique within a page, so using id selector (#div1) means it can only target a singular element with data key 'href' to show data value.

 

Using class (class means can be used multiple times within page) selector ref (div.aaa) only, means all elements using this class would be stored as a list, then together with

 

$("div.aaa").data("href","#222");

 

Means it would assign a data key of 'href' and value of '#222' to each element within that list using that class, but then you have the problem of targeting a specific element with this class, with this data key and this value compared to unique id ref where you target only one.

Link to comment
Share on other sites

I think it's kind of pointless to use the bloat of jQuery for things that are natively supported, and usually a lot faster when done natively.

 

var divs = document.querySelectorAll('div.aaa');
var div = document.querySelector('div.aaa[href=#222]');

for (var i = 0; i < divs.length; i++) {
  divs[i].addEventListener('click', function() {
    window.location = this.dataset.href; // data-href attribute
  });
}
Link to comment
Share on other sites

sorry WHAT! does this

 

var div = document.querySelector('div.aaa[href=#222]');

 

have to do with the rest of this

var divs = document.querySelectorAll('div.aaa');

 

for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener('click', function() {
window.location = this.dataset.href; // data-href attribute
});
}

 

Are we working with href attribute or dataset attribute or both?

 

All this for loop attachment of click event will do is throw up an error with every clicked div with class 'aaa' that does not have data-href.

 

href

$('div.aaa[href]').on('click', function() { window.location = $(this).attr("href"); });

 

data-href

$('div.aaa[data-href]').on('click', function() { window.location = $(this).data("href"); });

 

Note: in JavaScript use .getAttribute(), its for usual older versions of IE issue as usual

Link to comment
Share on other sites

sorry WHAT! does this

 

var div = document.querySelector('div.aaa[href=#222]');

 

have to do with the rest of this

Take your meds, it was an example line to show querySelector returning a single element using a complex selector. The point is that jQuery is not needed.

 

Are we working with href attribute or dataset attribute or both?

Could be either, I'm just showing examples. I pointed out on the line that uses dataset that it is specifically getting the data-href attribute, that's why I wrote that comment. The other selector looks for something different. I assume that people can look at that code and correlate it to jQuery with the purpose of understanding that jQuery is not necessary. If someone wants to understand how to develop using Javascript then I consider relying on jQuery to be an unnecessary crutch, especially when that jQuery code can be replaced with native code which will virtually always run much, much faster.

 

All this for loop attachment of click event will do is throw up an error with every clicked div with class 'aaa' that does not have data-href.

I'm sorry that I did not add more validation into my hypothetical example. I will leave that as an exercise for the reader.
Link to comment
Share on other sites

First of all, I have taken my meds thank you!

 

I will put this down as a bad example, could no! should have been better thought out with better explantion.

 

Faster? Minute difference and when compared to cross browser compatibility as shown with getAttribute() suggestion, I'll choose jQuery everytime rather waste time finding native cross browser alternative.

Link to comment
Share on other sites

I stick with getAttribute() for data attributes because I don't actually see an advantage to the more modern version. It's just what you'd call "syntactical sugar".

Link to comment
Share on other sites

Thats the problem, two methods old and new where you have tbe possibility to choose none cross-browser method, waste time finding out that crappy IE for instance does not yet fully support this method and you have to use altenative method, while with jQuery you would not have this problem.

Link to comment
Share on other sites

Faster? Minute difference

It might be a small difference in time, but jQuery code can run on the order of thousands or even millions of times slower than native functions. I understand that some programmers don't care about efficiency of the code they write, and don't care how it works. I'm not one of them.

 

I'll choose jQuery everytime rather waste time finding native cross browser alternative.

Yes, I don't waste time either. Apparently we have that in common. It's always good when someone doesn't choose to just waste their time. Meanwhile, my company now charges people to fix bugs even for IE10 (IE11 is the only version of IE with free bug fixes now). Guess how many complaints we've had about that policy. As far as a cross-browser alternative, what browser are you trying to support that is not on this list? I just had a request from the Air Force to help with a system that targets IE5, are you behind that?

 

I stick with getAttribute() for data attributes because I don't actually see an advantage to the more modern version. It's just what you'd call "syntactical sugar".

That's true, but just like I no longer use "array()" in PHP, I use dataset because it's quicker and easier.

 

while with jQuery you would not have this problem.

Right, instead you have an additional ~100KB download, plus horrible performance. You've traded one perceived problem (which is not an actual problem) for a different problem (which is an actual problem).

 

 

This can be argued until both of us are blue in the face, but it really boils down to this - if someone wants to be a proficient Javascript programmer, then jQuery is at best a performance-killing crutch and at worst a liability if you can only program using jQuery. Some might even claim that people who can only program using jQuery are not actually Javascript programmers.

Link to comment
Share on other sites

IE5 REALLY! Ha ha that explains a lot why we get blue on blue attacks by air force.

 

The caniuse site just proves my point! You used '.dataset', but IE6 to IE10 only work with getAttribute(), you are supposed to be experienced javascript developer but you failed to produce a correct cross-browser solution. But I suppose this would be good for you wasting time for air force project because this means you make more money taking longer to finish this project! Good thinking.

Link to comment
Share on other sites

Yes! I know that! Do you ever read previous posts? (See post#11) But! Using dataset instead of getAttribute() to read a custom data- attribute does not!

 

I'm just saying you don't need some odd polyfill to make a cross-browser solution. getAttribute() works 100% which negates the need for jQuery, which seems to be the point you were trying to make. jQuery is not any easier than vanilla JS for this particular solution.

Link to comment
Share on other sites

you are supposed to be experienced javascript developer but you failed to produce a correct cross-browser solution.

Ess Eye Gee Aitch. Pay attention to what I'm saying. In my world, cross-browser does not include IE6, IE10, or any other version of IE that is no longer supported by Microsoft. IE10 was EOL'd in January. Neither Microsoft nor our company supports it. If one of our customers finds a bug which only exists in IE10 and not IE11, they have to pay for us to spend our time to fix a bug in an unsupported browser that less than 1% of people use.

 

If you want to spend your time supporting old browsers, great, there's someone at the Air Force I can put you in touch with. My response was that they need to be able to change their system if it's going to work with our technology.

Link to comment
Share on other sites

You don't seem to get it! Using jquery you don't have to worrying about older version of browsers support, it offers cross-browser for old and new support without the need of wasting time AND money finding a solution for these browsers in plain javascript which is already provided with jquery, like i said 'good thinking' for unnecessary fixes in plain javascript that is already fixed using jquery. Don't worry i won't say anything nudge nudge wink wink.

Link to comment
Share on other sites

Using jquery you don't have to worrying about older version of browsers support

I already don't worry about that, and I don't even need jQuery to allow me to not worry.

 

Listen, when jQuery came out the current version of IE was 6. Back then, and even through the next few years, yeah it was useful to have a library that did the same thing in IE6 and Firefox, even if it was slower. It's not 2006 any more, though. Don't be afraid. Put down the crutch, I bet you can walk on your own if you tried it. You can use native methods in all but the most extreme situations. Take some pride in writing efficient code instead of importing an entire library just so that you can have a replacement for document.getElementById or document.getElementsByTagName or document.querySelectorAll which takes hundreds of times longer to execute (which is exactly what happened in this thread). Stop trying to track down plugins and other software that someone who's not you wrote that work in the version of jQuery that you're using.

 

Go ahead, give it a try. You can even select the individual parts of the framework you need so that the file you include is as small as possible. Don't bother with gzipping it though, with this library compression actually makes it larger.

Link to comment
Share on other sites

I rarely use plugins, I'm quite capable of producing my own code to produce the result i require, and another thing, using javascript to reproduce the same effect using jQuery triples the code required, your own wrong uncross-browser example proves it! I know its small amount code, but all this small combined amounts of code can add up.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...