19

How do you select and modify an element by it's title?

javascript: (function () {
  document.body.innerHTML += `<style>* {
    background:% 20#000 % 20!important;
    color:% 20#0f0 % 20!important;
    outline:% 20solid % 20#f00 % 201px % 20!important;
  } </style > `;
})();

I need to update the snippet / bookmarklet so when I run it (I have it on my bookmarks bar) it changes the position of a certain element in the document.

The only way I could select this element is by its title attribute.

2
  • 1
    so - what code have you tried, to select the item by title?
    – Taryn East
    Aug 13, 2014 at 2:33
  • Note: selecting something by name (rather than id) can work a little like this: "div[name=abcd]", so title might work that way too...
    – Taryn East
    Aug 13, 2014 at 2:34

1 Answer 1

57

CSS Selector

Use the selector notation for finding a node by it's attribute

[title="element title attribute value"]

Using JavaScript

Same selector as in CSS, but you can get the Node using document.querySelector, or if expecting multiple Nodes, a NodeList via document.querySelectorAll

var node = document.querySelector('[title="element title attribute value"]');

When you do .innerHTML, you are causing a re-parse of all HTML in the node you've called it on and this can literally destroy sections of web pages. You should use DOM methods for creating nodes, instead. e.g.

var style = document.createElement('style');
style.appendChild(document.createTextNode('div {border: 1px solid red}'));
document.body.appendChild(style);

Converting JavaScript into a bookmarklet is as simple as

bookmarklet = 'javascript:'
    + encodeURIComponent('(function () {' + code + '}())')
    + ';';

Here is a fiddle where you can just paste in code

2
  • It only gets the first element with that title. How do I get all of them? Feb 9, 2017 at 21:01
  • 4
    @KolobCanyon Use "querySelectorAll" instead of "querySelector"
    – Rut Shah
    Feb 4, 2020 at 21:59

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.