moar stupid jquery tricks
- 1 minutes read - 190 wordsSometimes it’s useful to use tampermonkey on a site without nice id
s for the elements you want to edit.
It turns out it’s still pretty easy!
Take my own website; I have <h2>
elements for the headers, but none of them have any id
s associated.
But as discussed in the jquery selectors post, we can still select by just the tag, with a selector like
$("h2")
This returns a jQuery
object, which behaves like an array.
If we want to select a particular one – like “Research Interests” – we can try accessing different elements until we get the one we want:
> $("h2")[0]
< <h2>Work</h2>
> $("h2")[1]
< <h2>Education</h2>
> $("h2")[2]
< <h2>Research Interests</h2>
One tricky bit here, though: doing the array access returns the dom element, not another jQuery
object!
The most direct API here is just using the textContent
DOM API to set the “text content” of that element, like
$("h2")[2].textContent = "RESEARCH INTERESTS"
But since we have been using jQuery so far, we can also call the $
with dom element, like:
$($("h2")[2])
and now we can call usual jQuery object methods, like #html
$($("h2")[2]).html("RESEARCH INTERESTS")