Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
589 views
in Technique[技术] by (71.8m points)

html - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...