0

I am trying to select all the anchors contained in a variable that is html as below my code:

var deposti_row = "
<a data-country='uk' data-currency='eur' data-matching='country-currency'> AA </a>
<a data-country='uk' data-currency='eur' data-matching='country'> BB </a>
<a data-country='uk' data-currency='eur' data-matching='none'> CC </a>
"

$("a['data-matching']",$(deposit_row)).each( function(){
console.log(this);
});

But i get the error Syntax error, unrecognized expression: a['data-matching'] . Any help please ?

1

3 Answers 3

2

Your syntax is wrong. Anyway, what you really want is to filter matched set:

$(deposit_row).filter('a[data-matching]').each(...)

And your string syntax is wrong too regarding handling mutliple lines. And deposti_row is not the same as deposit_row.

That makes many things wrong is so few posted code...

Sign up to request clarification or add additional context in comments.

3 Comments

Also, need to take care of multi-line text variable
@Satpal Ya good point. Indeed, many things wrong in OP posted code
@MrCode Sorry but which root element are you talking about? OP wants to filter out selection i guess
1

Heres another way:-

  1. create your multiline string with \.
  2. As theres no root, check with has inside your each.

var deposit_row = "\
<a data-country='uk' data-currency='eur' data-matching='country-currency'> AA </a>\
<a data-country='uk' data-currency='eur' data-matching='country'> BB </a>\
<a data-country='uk' data-currency='eur' data-matching='none'> CC </a>\
";

$(deposit_row).each(function() {
  if ($(this).has('[data-matching]'))
    console.log(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

1 Comment

I really don't think it is what OP is expecting.
0

You need to remove single quotes from the attribute selector, then it should work as long anchor tag a has a parent element.

You need to wrap them in a div to treat them as descendants

deposit_row = $(deposit_row).wrap("<div></div>").html();

$("a[data-matching]",$(deposit_row)).each( function(){
   console.log(this);
});

Also try this if a['data-matching'] is the child of a root node

$(deposit_row).find("a['data-matching']").each(function(){
});

But since a is the root node here

$(deposit_row).children("a['data-matching']").each(function(){
});

2 Comments

@RayonDabre i think he has given quotes to the attribute name
@Guru, Second argument in $ will act as parent of the selector...Much like .find().. Wrapping all a elements in any parent will help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.