简体   繁体   中英

JQuery get attribute value with same name

I want to get the href attr value based on the value of the rel attr . How do I do this in javascript?

<links>
    <link href="https://someurl/index/16380" rel="self"/>
    <link href="https://someurl/index/16380/streams?lang=en" rel="streams"/>
    <link href="https://someurl/index/16380/bif" rel="bif" />
</links>

something along the line ....

$(xml).find('link').each(function(){
 if(rel == 'streams'){
   this.streamurl = $(this).attr('href');
 }
});
$(xml).find("link[rel=streams]")
      .each(function(i,lnk) {
          lnk.streamurl = lnk.href; 
      })

Or

$(xml).find("link[rel=streams]")
      .prop("streamurl", function() {
          return this.href; 
      })

Your original code was almost correct. Just needed this:

if(this.rel == 'streams'){

instead of this:

if(rel == 'streams'){

Open your developer console, and you'd probably see something like:

ReferenceError: rel is not defined

$(xml).find('link').each(function(){

  //prevents your re-wrapping this multiple times
  var $this = $(this);

  //read the attribute
  if($this.attr('rel') == 'streams'){
     this.streamurl = $this.attr('href');
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM