0

Suppose i have a link such as

<a class="like_button" href="#" action_click="LikePost">I Like It</a>

How can i search the dom via pure JavaScript to scan the html for the action_click="LikePost" The code below doest not work for me

document.getElementsByTagName('action_click')

I feel though that a regular expression might needed.

Skeptic
  • 898
  • 10
  • 17

3 Answers3

3

Use document.querySelector

document.querySelector('[action_click="LikePost"]');

And if there are multiple such elements, use document.querySelectorAll which will return a live HTMLCollection.

document.querySelectorAll('[action_click="LikePost"]');
gurvinder372
  • 64,240
  • 8
  • 67
  • 88
1

You should use the querySelector() like that:

console.log(document.querySelector('[action_click="LikePost"]'));
<a class="like_button" href="#" action_click="LikePost">I Like It</a>
Takit Isy
  • 8,976
  • 3
  • 19
  • 46
1

If you have only one element with that attribute then querySelector works.

var elem = document.querySelector('[action_click="LikePost"]');
console.log(elem);
<a class="like_button" href="#" action_click="LikePost">

But if you have multiple elements then querySelectorAll is what you need:

var elem = document.querySelectorAll('[action_click="LikePost"]');
console.log(elem);
<a class="like_button" href="#" action_click="LikePost">
<a class="like_button" href="#" action_click="LikePost">
<a class="like_button" href="#" action_click="LikePost">
Ankit Agarwal
  • 29,658
  • 5
  • 35
  • 59
  • Thanks for the answer, it helped! Im using this JavaScript code within a python script, but even if JavaScript syntax is correct, the script refuses to run complaining about a syntax error. `driver.execute_script("window.a = document.querySelectorAll('[action_click="LikePost"]');")` I think im missing something – Skeptic May 02 '18 at 12:53