Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select an element by title with JavaScript and update it

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.

like image 859
Computer's Guy Avatar asked Aug 13 '14 02:08

Computer's Guy


People also ask

How do you select an element with a title attribute?

To select elements by an attribute name, pass a selector with the attribute's name to the querySelectorAll() method, e.g. document. querySelectorAll('[title]') . The querySelectorAll method will return a collection of the elements that have the provided attribute set.

How do I select a section tag in JavaScript?

To select a <select> element, you use the DOM API like getElementById() or querySelector() . How it works: First, select the <button> and <select> elements using the querySelector() method. Then, attach a click event listener to the button and show the selected index using the alert() method when the button is clicked.

What is Title in JavaScript?

The title attribute specifies extra information about an element. It can be shown as a tooltip text when the mouse moves over the element.


1 Answers

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

like image 78
Paul S. Avatar answered Sep 23 '22 07:09

Paul S.